Skip to main content

LEMP Stack Deep Dive

Course

Intro Video

Photo of Tom Dean

Tom Dean

Linux Training Architect II

Tom hails from Chicago, near the home of the South Side Irish Parade. He loves of ALL the seasons (which can happen at any moment in Chicago) and it was one of the things that brought him back to the area over ten years ago. When Tom is away from the keyboard he loves to tinker with vintage electronics, make music and occasionally hang out on his boat.

Length

10:00:00

Difficulty

Intermediate

Videos

28

Hands-on Labs

9

Course Details

In this course, you will gain a better understanding of the LEMP stack through lessons and hands-on labs. You will learn how to install a LEMP stack on both RHEL and Ubuntu Linux, perform basic configuration of NGINX, secure MariaDB and even deploy a PHP application on a LEMP stack. When you have finished the course you will have the skills necessary to build your own LEMP stack.

LEMP Stack Deep Dive Git Repository

Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive

What is the LEMP Stack? Linux NGINX (eNGINeX - the "E") MariaDB PHP LEMP Stack Deep Dive - Objectives What is the LEMP stack? How does it compare to a LAMP stack? How do you install a LEMP stack on RHEL / Ubuntu Linux? How do you configure NGINX? How do you configure and secure MariaDB? How do you deploy PHP applications using php-fpm? Deploy phpMyAdmin on Ubuntu Linux LEMP Stack Deep Dive - Prerequisites Beginner to intermediate Linux command-line skills Experience with configuring web servers on Linux is a plus Experience with web development is a plus, but not required No DBA skills required No programming skills required LEMP Stack Deep Dive - Labs Install LEMP Stack on RHEL / Ubuntu Linux Basic Configuration of NGINX Generate SSL Certificates Advanced Configuration of NGINX Customize Logging in NGINX Configure and Secure MariaDB Configure php-fpm Deploy phpMyAdmin

Syllabus

Getting Started

About the Course / Prerequisites

00:03:52

Lesson Description:

In this lesson, we are going to preview the LEMP Stack Deep Dive course. We will talk about the scope of the course and what skills and experience you should bring to the course. When you finish this lesson you should have a good understanding of what the course is about. LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive Ratings and Feedback Throughout the course, in the lessons and labs, as well as for the entire course itself, are opportunities to provide feedback (thumbs up, thumbs down). I appreciate your feedback as it not only helps me make this course better, but future courses as well. If you liked the lesson / lab / course and would like to make a suggestion, but want to also give it a "thumbs up" you can do that as well! Flash Cards Feel free to check out the Flash Cards for the course to test your knowledge! They are accessible from the main course page as well as in the upper right-hand corner of the lesson pages. Linux Academy Community Another resource to assist you in your learning adventure is the Linux Academy Community. You can access Community via the upper navigation bar. I hope you enjoy the course! LEMP Stack Deep Dive - ObjectivesWhat is the LEMP stack? How does it compare to a LAMP stack? How do you install a LEMP stack on RHEL / Ubuntu Linux? How do you configure NGINX? How do you configure and secure MariaDB? How do you deploy PHP applications using php-fpm? Deploy phpMyAdmin on Ubuntu LinuxLEMP Stack Deep Dive - PrerequisitesBeginner to intermediate Linux command-line skills Experience with configuring web servers on Linux is a plus Experience with web development is a plus, but not required No DBA skills required No programming skills requiredLEMP Stack Deep Dive - LabsInstall LEMP Stack on RHEL / Ubuntu Linux Basic Configuration of NGINX Generate SSL Certificates Advanced Configuration of NGINX Customize Logging in NGINX Configure and Secure MariaDB Configure php-fpm Deploy phpMyAdmin

About the Training Architect

00:01:03

Lesson Description:

Get to know your Training Architect, Tom Dean. Reference Links Tom Dean on LinkedIn Tom Dean Linux Training Architect Over 20 years experience in Information Technology

- Focus on Linux / UNIX
- Traditional and virtualized infrastructure
- Managed teams and projects
- Exposure to many industries / environments
- Have worked with Linux since 1997
- Focus has been on RedHat distributions
- Passion for Linux and Open Source 
Started on Apple IIs in the early 1980s: - Programming in BASIC - Hacking in general Purdue University graduate: - First exposure to UNIX on Sequent 386-based systems - First exposure to the Internet (just before WWW was widespread) Interests: - Boating - Obsolete electronics - Music - Household projects Thank you for choosing Linux Academy as your learning partner, and for allowing me to assist you with your journey!

Big State College - A Case Study

00:03:02

Lesson Description:

In this lesson, you will be introduced to the scenario for the labs in the LEMP Stack Deep Dive course, Big State College. Big State College (BSC) is a Large Ten Conference school in a Midwestern state. BSC is looking to deploy a centralized web hosting service. BSC's existing environment is a patchwork of various, often antiquated LAMP stacks. There are also lot of "rogue" LAMP stacks amongst the various schools and research institutions. All these LAMP stacks will be consolidated into the new LEMP hosting environment. LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive Motivations Driving the LEMP ProjectSecurity / Patching concerns Support concerns New web server features

          - Functionality / features / security
          - Development / QA / production environments
Other challenges, current and futureBSC's Requirements:Want to use the NGINX and the LEMP stack Want to consolidate the large number of independent LAMP stacks into? the new LEMP environment Want to deploy a customized configuration for multitenancy: "Home directories" with WWW, SSL certs and per-site logs Virtual Hosts HTTPS only: Redirect all requests to HTTPSBig State College has decided to employ a dual-OS strategy in the LEMP hosting environment and will be utilizing both RHEL 8 and Ubuntu Linux to host their various shared web environments and supporting applications. As the engineers tasked with executing this project, we will learn how to install, configure and deploy applications on top of the LEMP stack as part of building the new hosting environment.

Introduction to the LEMP Stack

What is the LEMP Stack?

00:07:05

Lesson Description:

In this lesson, you will be introduced to the LEMP Stack. We will cover web stacks, the LAMP Stack, and the evolution toward the LEMP Stack. We will talk about the role of Linux in the LEMP Stack and how to choose a distribution. When this lesson is complete, we will have a better understanding of what the LEMP Stack is and a high-level understanding of how one is put together. LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive What is a Web Stack? A Web Stack is a set of components or technologies that, when combined, constitute a framework on which web sites live. Examples of Web StacksLAMP / WAMP / MAMP / XAMP LEMP: A variation on LAMP WISA (Microsoft) : Windows / IIS / SQL Server / ASP.NET OthersWhat is the LEMP Stack?Linux (Operating System) eNGINeX (Web Server) MariaDB (Database) PHP (Scripting Language)Linux - Choosing a Distribution Considerations:Support needs / subscription costs Staffing needs / skills Repositories / availability Application support Hardware / hypervisor supportLEMP - Scalability / Fault ToleranceSingle server or multiple servers: Load balancing (NGINX) Highly-available databaseNGINX and MariaDB can live on their own servers NGINX is known for being high performance NGINX can proxy other applications / websites (even Apache / IIS!)LEMP - In Reality...Most environments are not as cut and dried as a single ? stack on a single server: Application needs Legacy environments Organizational factors The cloud Mergers / acquisitions Other factorsThe NGINX component of the stack can serve to unite all these elements

NGINX - The Engine of the Stack

00:04:13

Lesson Description:

The web server is the heart of any web stack. It's how the outside world accesses the data and applications on the site(s) living on the stack. In this lesson, we will take a look at NGINX, the new kid on the block in high-performance, flexible web servers. We'll take a look at the origin of NGINX, it's features, the additional features that NGINX Plus offers, and compare NGINX with the Apache Web Server. Upon completion of this lesson, you will have a solid high-level understanding of NGINX. Reference Links nginx Nginx - Wikipedia LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive NGINX "nginx [engine x] is an HTTP and reverse proxy server, a mail proxy server, and a generic TCP/UDP proxy server, originally written by Igor Sysoev. For a long time, it has been running on many heavily loaded Russian sites including Yandex, Mail.Ru, VK, and Rambler. According to Netcraft, nginx served or proxied 25.69% of the busiest sites in October 2019. Here are some of the success stories: Dropbox, Netflix, Wordpress.com, FastMail.FM. The sources and documentation are distributed under the 2-clause BSD-like license. Commercial support is available from Nginx, Inc." Basic HTTP Server FeaturesServing static and index files, autoindexing Open file descriptor cache Load balancing and fault tolerance Accelerated reverse proxying with caching Accelerated support with caching of FastCGI, uwsgi, SCGI, and memcached servers Modular architecture. Filters include gzipping, byte ranges, chunked responses, XSLT, SSI, and image transformation filter. Multiple SSI inclusions within a single page can be processed in parallel if they are handled by proxied or FastCGI/uwsgi/SCGI servers SSL and TLS SNI support Support for HTTP/2 with weighted and dependency-based prioritizationOther HTTP Server FeaturesName-based and IP-based virtual servers Keep-alive and pipelined connections support Access log formats, buffered log writing, fast log rotation, and syslog logging 3xx-5xx error codes redirection The rewrite module: URI changing using regular expressions Executing different functions depending on the client address Access control based on client IP address, by password (HTTP Basic authentication) and by the result of subrequest Validation of HTTP referer The PUT, DELETE, MKCOL, COPY, and MOVE methods FLV and MP4 streaming Response rate limiting Limiting the number of simultaneous connections or requests coming from one address IP-based geolocation A/B testing Request mirroring Embedded Perl njs scripting languageMail Proxy Server FeaturesUser redirection to IMAP or POP3 server using an external HTTP authentication ? server User authentication using an external HTTP authentication server and connection ? redirection to an internal SMTP server Authentication methods: POP3: USER/PASS, APOP, AUTH LOGIN/PLAIN/CRAM-MD5 IMAP: LOGIN, AUTH LOGIN/PLAIN/CRAM-MD5 SMTP: AUTH LOGIN/PLAIN/CRAM-MD5SSL support STARTTLS and STLS supportTCP/UDP Proxy Server FeaturesGeneric proxying of TCP and UDP SSL and TLS SNI support for TCP Load balancing and fault tolerance Access control based on client address Executing different functions depending on the client address Limiting the number of simultaneous connections coming from one address Access log formats, buffered log writing, fast log rotation, and syslog logging IP-based geolocation A/B testing njs scripting languageNGINX vs NGINX Plus There are two versions of NGINX - OSS NGINX - NGINX Plus NGINX Plus comes with support and additional features - Active health checks - Session persistence (cookies) - DNS-Service-Discovery integration - Cache purging API - AppDynamic, Datalog, Dynatrace New Relic Plug-Ins - Active-Active HA with configuration synchronization - Key-value store - Web application firewall (WAF) dynamic module NGINX vs Apache NGINXNewer Better performance, serving static files: Low Memory Footprint (~2.5 MB per 10k inactive HTTP keep-alive connections) Approximately 4x Faster than Apache (stock configuration, serving static files)ApacheMature: long track record More flexibility (.htaccess files) Ease of deployment Large install baseNGINX - Popularity *"According to Netcraft's November 2016 Web Server Survey, Nginx was found to be the second-most widely used web server across all "active" sites (18 percent of surveyed sites) and for the top million busiest sites (28 percent of surveyed sites). According to W3Techs, it was used by 38 percent of the top 1 million websites, 50 percent of the top 100,000 websites, and by 57 percent of the top 10,000 websites. According to BuiltWith, it is used on 38 percent of the top 10,000 websites, and its growth within the top 10k, 100k and 1 million segments increased. A 2018 survey of Docker usage found that Nginx was the most commonly deployed technology in Docker containers. Wikipedia uses Nginx as its SSL termination proxy."* NGINX - SummaryHTTP/S web server Built for performance Low memory overheadLoad-balancing functionality Proxying / caching functionality Many advanced features Included in the standard repositories for many Linux distributions Growing market share

Why MariaDB?

00:04:34

Lesson Description:

The database is an important part of the web stack. For years, MySQL was the foundation of the LAMP Stack. The LEMP Stack brings us MariaDB, the next evolution of MySQL. In this lesson, we will learn what the role of a database is in the web stack, the history of MySQL and MariaDB, MySQL and MariaDB's similarities and differences, and options for MariaDB in the cloud. Upon completion of this lesson, you will have a good high-level understanding of MariaDB. Reference Links MySQL - Wikipedia About MariaDB Server - MariaDB.org MariaDB vs MySQL, a Database Technologies Rundown MariaDB Knowledge Base LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive Why a Database? What's the role of a database in the Web Stack? Typically, web sites and applications need a place to store their data. A database management system gives developers a place to store their data and access it using SQL. The website can then use a language, such as PHP, to access this data and generate dynamic web content with it. Some examples of SQL databases are MySQL, MariaDB, SQL Server, and Oracle. LAMP / MySQL - The Early Days The LAMP stack has been around almost as long as the WWW. A key part of this stack is MySQL. Oracle Acquires MySQL MySQL was originally an Open Source database project:First release - 23 May 1995 Sun Microsystems acquired MySQL AB in 2008 Oracle acquired Sun Microsystems on 27 January 2010 The day Oracle announced the purchase of Sun, and therefore MySQL, ? Michael "Monty" Widenius forked MySQL, creating MariaDBAbout MariaDB "MariaDB Server is one of the most popular database servers in the world. It’s made by the original developers of MySQL and guaranteed to stay open source. Notable users include Wikipedia, WordPress.com and Google. "MariaDB turns data into structured information in a wide array of applications, ranging from banking to websites. It is an enhanced, drop-in replacement for MySQL. MariaDB is used because it is fast, scalable and robust, with a rich ecosystem of storage engines, plugins and many other tools make it very versatile for a wide variety of use cases. "MariaDB is developed as open source software and as a relational database it provides an SQL interface for accessing data. The latest versions of MariaDB also include GIS and JSON features." MariaDB vs MySQL These two database management systems are quite different, despite MariaDB being a fork of MySQL:MariaDB is fully GPL licensed. MySQL offers both commercial and ? community licenses. Each handles thread pools in a different way. MariaDB supports a variety of different storage engines. MariaDB offers improved performance in many situations.MariaDB vs MySQL - Compatibility The whole point of forking MySQL off into MariaDB, which is named after Michael’s daughter, was to secure future access to MySQL and its further development. MariaDB was is a full binary replacement (“drop-in” replacement, so to say), that enables all users of MySQL to exchange one for the other on their systems. MySQL is a client-server application, and both its server program mysqld, its client mysql, and auxiliary programs, like mysqldump, retain the same name with MariaDB. Replacing MySQL with MariaDB is usually a seamless process for most applications and purposes, especially WordPress. Existing software, from popular CMS tools to apps like phpMyAdmin, work right out of the box, and can import/export actual data to and from one into another without any configuration changes. MariaDB’s stated goal is to maintain compatibility with MySQL. According to the MariaDB website:Data and table definition files are compatible. All client APIs and protocols are compatible. Filenames, binaries, and paths are the same on MySQL and MariaDB. Ports and sockets are the same. All MySQL connectors, PHP, Perl, Python, Java, and others, work with MariaDB. The MySQL client package works interchangeably with MariaDB, just as with ? MySQL.There are merges conducted monthly to ensure compatibility, and to get any new features and bug fixes from Oracle. MariaDB vs MySQL - Differences Features MariaDB has fixed a MySQL problem similar to one in Apache that Nginx addressed. Apache (and MySQL) assign threads to every client connection, and this "thread pool" is inefficient. It's like packing too much for a short vacation, instead of just picking things up (lipstick, razors, etc.) once you've arrived. MariaDB introduced its own solution to this in version 5.5 Invisible columns are MariaDB’s exclusive feature from 10.3.3. They do not return results in a SELECT * statement, nor do they need to be assigned a value in an INSERT statement. MariaDB has introduced database views, a significant optimization feature that only queries necessary tables. Some features MySQL introduced are JSON native data type, MySQL Shell in MySQL 8.0 version (which allows Javascript and Python scripting, and doesn’t work with MariaDB), and SHA-256-based authentication plugin, which improves security over mysql_native_password. Storage Engines MariaDB: XtraDB, InnoDB, MariaDB ColumnStore, Aria, Archive, Blackhole, Cassandra Storage Engine, Connect, CSV, FederatedX, Memory storage engine, Merge, Mroonga, MyISAM, MyRocks, QQGraph, Sequence Storage Engine, SphinxSE, Spider, TokuDB and ColumnsStore MySQL: InnoDB, MyISAM, Memory, CSV, Archive, Blackhole, Merge, and Federated MariaDB - In the CloudAmazon RDS for MariaDB Google Cloud - Cloud SQL Fully managed database service for MySQL, PostgreSQL, and SQL Server.Azure Database for MariaDBMany hosting providers offer hosted MariaDB as well MariaDB - SummaryMariaDB was created as a response to Oracle's acquisition of Sun ? Microsystems, and MySQL AG, in 2010. MariaDB is fully open-source. MariaDB is a "drop-in binary replacement" for MySQL. There are some feature differences. Commercial support is available for MariaDB.MariaDB Knowledgebase

PHP - Follow the Script

00:05:03

Lesson Description:

PHP is the part of the LEMP Stack that makes rich, interactive websites and applications possible. In this lesson, we will learn what PHP is and about PHP's history. We will also examine how PHP fits into the LEMP Stack and how PHP code is processed using PHP-FPM. We will take a look at some sample PHP code and will also look at the pros and cons of PHP. Upon completion of this lesson, you will have a good high-level understanding of PHP and its role in the LEMP Stack. Reference Links PHP: What is PHP? - Manual PHP: History of PHP - Manual PHP - Wikipedia Lesson Objectives:Learn about PHP and its history Explore the role of PHP in the LEMP Stack Explore the pros and cons of PHP Learn about the role of PHP and php-fpm in the LEMP StackWhat is PHP? PHPRecursive acronym for PHP: Hypertext Preprocessor A widely-used open source general-purpose scripting language Especially suited for web development Can be embedded into HTML Is executed on the server side, returns HTML Code is hidden from the clientHistory of PHP PHP development began in 1994 when Rasmus Lerdorf wrote several Common Gateway Interface (CGI) programs used to maintain his personal homepage.PHP Tools (Personal Home Page Tools) - June 1995 FI (Forms Interpreter) - October 1995 Personal Home Page Construction Kit PHP/FI - April 1996 PHP 3.0 - June 1998 PHP 4.0 - May 2000 PHP 5 - July 2004 PHP 7 - December 2015Pros and Cons of PHP ProsLow barrier to entry Open SourceSecure (HTML output) Wide choice of operating systems / web stacks Large community Easily embedded into HTMLConsHTML experience required Performance Not optimized for desktop appsPHP Usage *"As of August 2019, PHP was used as the server-side programming language on 79.1% of websites, down from 83.5% previously, where the language could be determined. Web content management systems written in PHP include MediaWiki, Joomla, eZ Publish, eZ Platform, SilverStripe, WordPress, Drupal, and Moodle. Websites written in PHP, in the back-end and/or user-facing portion, include Facebook, Digg, Tumblr, Dailymotion, and Slack."*

Installing a LEMP Stack on Linux

Installing LEMP on RHEL 8

00:09:54

Lesson Description:

Before you build a house, you have to lay the foundation. And before you can build a great website or application, you will need a web stack on which to build it. In this lesson, we're going to cover what a web stack and the LEMP Stack are, and how to install the LEMP Stack on RHEL 8. When you finish this lesson, you will know how to install a LEMP Stack on a modern Red Hat Linux distribution. Let's go! LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive What is a Web Stack? A Web Stack is a set of components or technologies that, when combined, constitute a framework on which web sites live. What is the LEMP Stack?Linux (Operating System) eNGINeX (Web Server) MariaDB (Database) PHP (Scripting Language)LEMP / RHEL 8 Some things that you'll find on RHEL 8 LEMP installations:The yum command is used to install LEMP stack components Services are not enabled and started when installed by yum. This has to be done via systemctl Default document location is /usr/share/nginx/html SELinux issues may arise with customized configurations.LEMP Installation on RHEL 8 Step 1: Install NGINX Using the Default RHEL Package Repositories Become the root user:

sudo su -
Install the NGINX server using yum:
yum -y install nginx
Enable the NGINX server to start at boot time via systemctl:
systemctl enable nginx
Before we start NGINX, we want to validate the NGINX configuration:
nginx -t
Start the NGINX server using systemctl:
systemctl start nginx
Check the NGINX service status using systemctl:
systemctl status nginx
Step 2: Configure HTTP Access Through the Firewall Check the firewall configuration for the current state using firewall-cmd:
firewall-cmd --info-zone=public
Allow traffic on port 80 (HTTP) through the firewall:
firewall-cmd --zone=public --add-service=http --permanent
Reload the new firewall configuration to pick up the change:
firewall-cmd --reload
Step 3: Verify Basic HTTP Functionality in NGINX Use curl to verify that the default NGINX web page loads:
curl http://`curl v4.ifconfig.co`
Use a web browser to go to the default NGINX web page at http://PUBLIC_IP_ADDRESS or http://PUBLIC_DNS_ADDRESS. The default NGINX page should be there. The public IP address and DNS of the instance is in /home/cloud_user/server_info.txt. Step 4: Install the PHP Components Install the PHP components using yum:
yum -y install php php-pdo php-mysqlnd php-gd php-mbstring php-fpm
You may notice that php-fpm is already installed. This is not an error, as php-fpm was installed during the creation of the lab environment. Step 5: Verifying PHP Functionality in NGINX Load the phpinfo page using curl. Notice that we are specifying a header (using the -H option) so that the proper virtual host is accessed:
curl -H "www.testdomain.local" http://www.testdomain.local/phpinfo.php
You should see the 'phpinfo' page for this server. If you put your server's public IP address into your /etc/hosts file pointing to www.testdomain.local, you should be able to access the 'phpinfo' page at http://www.testdomain.local/phpinfo.php using a web browser. Step 6: Install MariaDB Install MariaDB using yum:
yum -y install mariadb mariadb-server
Use systemctl to 'enable' and 'start' MariaDB:
systemctl enable mariadb
systemctl start mariadb
Use systemctl to verify that MariaDB is installed, 'enabled', and 'running':
systemctl status mariadb
Step 7: Verify the Installed Version of MariaDB Verify the installed version of MariaDB, using mysql -V:
mysql -V
The exact version is not critical here, but we want to confirm it returns a result. In this lesson, we:Installed a LEMP stack on RHEL 8 Demonstrated NGINX serving static (HTML / Text) and dynamic (PHP) contentNow that you have a LEMP stack installed and running on RHEL 8, you can proceed with configuring NGINX and MariaDB so you can build your website/application!

Installing LEMP on Ubuntu Linux

00:10:00

Lesson Description:

Before you build a house, you have to lay the foundation. And before you can build a great website or application, you will need a web stack on which to build it. In this lesson, we're going to cover what a web stack and the LEMP Stack are, and how to install the LEMP Stack on Ubuntu Linux. When you finish this lesson, you will know how to install a LEMP Stack on Ubuntu Linux. Let's go! LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive What is a Web Stack? A Web Stack is a set of components or technologies that, when combined, constitute a framework on which web sites live. What is the LEMP Stack?Linux (Operating System) eNGINeX (Web Server) MariaDB (Database) PHP (Scripting Language)LEMP / Ubuntu Linux Some things that you'll find on Ubuntu Linux LEMP installations:LEMP stack components are installed using apt-get or apt. Services are enabled and started when installed via apt-get. Default NGINX configuration includes the 'sites-enabled' and 'sites-available' directories for virtual host configuration files. Default document location is /var/www/htmlLEMP Installation on Ubuntu Linux Step 1: Install NGINX Using the Default Ubuntu Package Repositories Become the root user:

sudo su -
Install NGINX from the Ubuntu repositories using apt-get:
apt-get -y install nginx
Check the NGINX service status using systemctl:
systemctl status nginx
The NGINX service should be 'enabled' and 'active'. Step 2: Configure HTTP Access Through the Firewall Check the initial status of the firewall using ufw:
ufw status
Open port 80 to allow inbound HTTP traffic:
ufw allow 'Nginx HTTP'
Recheck the status of the firewall:
ufw status
Step 3: Verify Basic HTTP Functionality in NGINX Use curl to verify that the default NGINX web page loads:
curl http://`curl v4.ifconfig.co`
Use a web browser to go to the default NGINX web page at http://PUBLIC_IP_ADDRESS or http://PUBLIC_DNS_ADDRESS. The default NGINX page should be there. The public IP address and DNS of the instance is in /home/cloud_user/server_info.txt. Step 4: Install the PHP Components Install the PHP components using apt-get:
apt-get -y install php-fpm php-mysql
Step 5: Verifying PHP Functionality in NGINX In order to test PHP, we will need to enable the www.testdomain.local site. NGINX under Ubuntu accomplishes this by using two directories, the 'sites-available' and the 'sites-enabled' directories. All available server blocks (configuration files for virtual hosts) are placed in 'sites-available'. When you want to make a virtual host active, you create a symbolic link to the appropriate configuration file in 'sites-enabled':
ln -s /etc/nginx/sites-available/testdomain.local.conf /etc/nginx/sites-enabled/testdomain.local.conf
We will now validate the NGINX configuration before reloading the NGINX service, using nginx -t:
nginx -t
If everything checks out, reload the NGINX service:
systemctl reload nginx
If you'd like to check the status of the NGINX service, use systemctl.
systemctl status nginx
We also need to reload the php-fpm service.
systemctl restart php7.2-fpm.service
Verify that PHP is functioning by loading the phpinfo page on the www.testdomain.local virtual host, using the curl command. Note that we are providing a header for the request (via the -H switch) so NGINX knows to route the request to the www.testdomin.local virtual host.
curl -H "www.testdomain.local" http://www.testdomain.local/phpinfo.php
You should see the 'phpinfo' page for this server. If you put your server's public IP address into your /etc/hosts file pointing to www.testdomain.local, you should be able to access the 'phpinfo' page at http://www.testdomain.local/phpinfo.php using a web browser. Step 6: Install MariaDB Install MariaDB using apt-get:
apt-get -y install mariadb-server
Check the status of the MariaDB server using systemctl:
systemctl status mariadb
The server should be 'enabled' and 'running'. Step 7: Verify the Installed Version of MariaDB Verify the installed version of MariaDB, using mysql -V:
mysql -V
The exact version is not critical here, but we want to confirm it returns a result. Summary In this lesson, we:Installed a LEMP stack on Ubuntu Linux Demonstrated NGINX serving static (HTML / Text) and dynamic (PHP) contentNow that you have a LEMP stack installed and running on Ubuntu, you can proceed with configuring NGINX and MariaDB so you can build your website/application!

Hands-on Labs are real live environments that put you in a real scenario to practice what you have learned without any other extra charge or account to manage.

00:45:00

Hands-on Labs are real live environments that put you in a real scenario to practice what you have learned without any other extra charge or account to manage.

00:45:00

Configuring the NGINX Server

NGINX - Resources and Documentation

00:02:52

Lesson Description:

In this lesson, we are going to introduce you to the nginx.org website. The website is a rich resource and will assist you with installing, configuring, and maintaining your NGINX environment. When this lesson is complete, you should have a better understanding of how the nginx.org website can be a fantastic tool for anyone working with NGINX. Reference Links NGINX Website Course: NGINX Web Server Deep Dive | Linux Academy LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive

Basic NGINX Server Configuration

00:08:08

Lesson Description:

In this lesson, we will explore the basic configuration of the NGINX web server. We will look at the /etc/nginx directory, the nginx.conf configuration file, virtual host configuration file locations, how and why we validate NGINX configurations, and how to reload and restart NGINX. When you are finished with this lesson, you will have a basic understanding of how NGINX is configured, and how and why to perform the basic steps to update your NGINX configuration. Reference Links Core functionality - pid Core functionality - worker_processes Core functionality - worker_connections Core functionality - include NGINX - Beginner’s Guide Course: NGINX Web Server Deep Dive | Linux Academy LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive Lesson Objectives:Explore the /etc/nginx directory Explore the nginx.conf file Learn how to check the NGINX configuration using nginx -t Learn how to reload the NGINX configurationThe /etc/nginx directory: Location for all configuration files:nginx.conf Virtual host configuration files: conf.d directory sites-available directory sites-enabled directoryModule configuration files: conf.d directory modules-available directory modules-enabled directoryThe nginx.conf file: Defines global configuration Server process configuration:User server runs as Location of PID filePerformance:worker_processes worker_connectionsLocation(s) of module and virtual host configuration files (via include) How to check the NGINX configuration: Use nginx -t before every reload! Reloading the NGINX Configuration:Using systemctl:

- **Reload** - Doesn't drop existing connections
- **Restart** - Drops existing connections
Using NGINX - nginx -s:
- *Validates the configuration before restarting*
The safe bet is to execute nginx -t before a reload or restart!

NGINX - Configuring Virtual Hosts

00:06:35

Lesson Description:

In this lesson, we will look at basic virtual host configuration in NGINX. We will review the locations for virtual host configuration files, create and test a new virtual host configuration, and explore troubleshooting errors in virtual host configuration files. When you are done with this lesson, you should be ready to configure your own virtual hosts in NGINX. Reference Links Core functionality - include Module ngx_http_core_module - server Module ngx_http_core_module - listen Module ngx_http_core_module - root Module ngx_http_core_module - server_name Module ngx_http_core_module - location NGINX - Beginner’s Guide Course: NGINX Web Server Deep Dive | Linux Academy LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive NGINX - Configuring Virtual Hosts Lesson Objectives:Explore virtual host configuration file locations Explore relationship between nginx.conf and virtual host server configuration blocks Review the contents of a virtual host configuration file Explore troubleshooting problems in virtual host configuration filesVirtual host configuration file locations:/etc/nginx/conf.d /etc/nginx/sites-available /etc/nginx/sites-enabledVirtual host configuration files are pulled into nginx.conf via include Virtual Host Configuration Files: Will have a server block, at a minimum:listen <port>; root /some/location; server_name name(s); location <directory>;Contains a place to "isolate" configuration for a single virtual host:Enable/disable single virtual host Easier to troubleshoot Easier to recover from issue(s)Troubleshooting Virtual Hosts: Use nginx -t to validate server configuration every time! Errors tell the source/nature of the issue:What the error is Which file the error is located in Line the error is on in that fileThis is why we isolate virtual host configuration files!

Configuring Custom Error Pages in NGINX

00:06:09

Lesson Description:

In this lesson, we will examine how we configure NGINX to handle custom error pages. We will configure a custom error page for a single error type, as well as for multple error types. When you finish this lesson, you should be able to configure custom error pages in NGINX. Reference Links Module ngx_http_core_module - error_page Course: NGINX Web Server Deep Dive | Linux Academy LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive Configuring Custom Error Pages in NGINX Lesson Objectives:Discuss why we might want to use custom error pages Demonstrate how to configure a custom error page for a single error type Demonstrate how to map a custom error page for multiple error typesWhy Custom Error Pages?Match "look and feel" of the site Provide customized information "Sanitize" server information "Catch all" for response codes that don't require a unique error page Configure "custom" action to one or more response codesConfigure a Single Error: Custom error pages are configured using the error_page directive:

        error_page 404 /testdomain_404.html;
        location = /testdomain_404.html {
                root /var/www/html;
                internal;
        }
This does the same thing, but returns a 200 status (OK) instead of 404:
        error_page 404 =200 /testdomain_404.html;
        location = /testdomain_404.html {
                root /var/www/html;
                internal;
        }
Map Multiple Errors to a Page We can map more than one response code to a single page using the error_page directive, as shown here:
        error_page 404 403 /testdomain_other_error.html;
        location = /testdomain_other_error.html {
                root /var/www/html;
                internal;
        }

NGINX - Directives - Upstream / Location / Return

00:08:55

Lesson Description:

In this lesson, we will examine some of the more popular directives in NGINX. We'll cover the upstream, location and return directives, three directives you will use all the time with NGINX. Upon completion of this lesson, you will understand how to use the upstream, location and return directives. Reference Links Module ngx_http_upstream_module Core HTTP functionality - location Module ngx_http_rewrite_module - return Course: NGINX Web Server Deep Dive | Linux Academy LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive NGINX - Directives - Upstream / Location / Return Lesson Objectives:Explore the upstream directive Explore the location directive Explore the return directiveThe upstream directive The upstream directive defines groups of servers that can be referenced by the proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, memcached_pass, and grpc_pass directives:

upstream testdomainapp  {
   server app1.testdomain.local:8085;
   server app2.testdomain.local:8086 backup;
   server app3.testdomain.local:8087 backup;
}
By default, requests are distributed between the servers using a weighted round-robin balancing method. The location directive The location directive sets configuration depending on a request URI:
location / {
        try_files $uri $uri/ =404;
}
location ~ /.ht {
        deny all;
}
A location can either be defined by a prefix string, or by a regular expression. The return directive The return directive stops processing and returns the specified code to a client:
location /downloads {
        rewrite ^(/downloads)/(.*)$ http://downloads.testdomain.local:9084/$2 permanent;
        return 403;
}

NGINX - Rewrites - An Introduction

00:05:06

Lesson Description:

In this lesson, we will examine basic rewrite functionality in NGINX. We will break down a few rewrite examples, and test a rewrite in real-time. When you finish this lesson, you should have a basic understanding of rewrites in NGINX and how to configure them. Reference Links How to Create NGINX Rewrite Rules | NGINX Module ngx_http_rewrite_module Course: Mastering Regular Expressions | Linux Academy Hands-On Lab - Working with Basic Regular Expressions Course: NGINX Web Server Deep Dive | Linux Academy LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive Lesson ObjectivesExplore the rewrite directive Examine some examples of the rewrite directiveThe rewrite directive: Changes part or all of the URL in a client request:To inform clients that the resource they’re requesting now resides at a different location To control the flow of processing within NGINX: Example: To forward requests to an application server when content needs to be generated dynamicallySample Rewrites

rewrite ^(/download/.*)/media/(w+).?.*$ $1/mp3/$2.mp3 last;
rewrite ^(/download/.*)/audio/(w+).?.*$ $1/mp3/$2.ra  last;
return  403;
location /download/ {
    rewrite ^(/download/.*)/media/(.*)..*$ $1/mp3/$2.mp3 break;
    rewrite ^(/download/.*)/audio/(.*)..*$ $1/mp3/$2.ra  break;
    return  403;
}
Example of the rewrite directive, used inside a location directive that uses an external URL:
location /downloads {
        rewrite ^(/downloads)/(.*)$ http://downloads.testdomain.local:9084/$2 permanent;
        return 403;
}
This rewrite grabs the file name after /downloads and sends the request to the URL: http://downloads.testdomain.local:9084/filename For more information on regular expressions, you can check out the Mastering Regular Expressions course in the Reference Links above.

NGINX - Load Balancing - An Introduction

00:05:06

Lesson Description:

In this lesson, we will examine NGINX's built-in load balancing features. We will use the upstream, location and server directives to configure and test load balancing in NGINX. When you are finsihed with this lesson, you should have a good high-level understanding of load balancing in NGINX and how to configure it. Reference Links Module ngx_http_upstream_module Module ngx_http_core_module - location Module ngx_http_upstream_module - server Course: NGINX Web Server Deep Dive | Linux Academy LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive NGINX - Load Balancing - An Introduction Lesson Objectives Explore load balancing using the:upstream directive location directive server directiveThe upstream directive The upstream directive defines groups of servers that can be referenced by the proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, memcached_pass, and grpc_pass directives:

upstream testdomainapp  {
   server app1.testdomain.local:8085;
   server app2.testdomain.local:8086 backup;
   server app3.testdomain.local:8087 backup;
}
By default, requests are distributed between the servers using a weighted round-robin balancing method. The location directive The location directive is the other part of the equation that enables the upstream directive:
location /app {
        proxy_pass http://testdomainapp/;
}
In this example, we are using the /app location to front-end the testdomainapp server group, defined in the upstream directive. The server directive The server directive defines an individual server that is part of the upstream group:
upstream testdomainapp  {
   server app1.testdomain.local:8085 weight=3;
   server app2.testdomain.local:8086;
   server app3.testdomain.local:8087 backup;
}
There are may options available to define how each server is handled in the group. Server parameters available in the non-commercial NGINX offering include:weight=<number> - Sets the weight of the server, default=1 max_conns=<number> - Limits active connections, default=0 max_fails=<number> - Maximum unsuccessful connections, default=1 fail_timeout=<time> - Sets fail timeout, default=10 seconds backup - Marks the server as a backup server down - Marks the server as a unavailable

Blocking Access by IP with NGINX

00:03:28

Lesson Description:

In this lesson, we will examine how to block IP requests using NGINX. We will take a look at the ngx_http_access_module and the associated allow and deny directives. Upon completion of this lesson, you will understand and be able to configure access restrictions in NGINX. Reference Links Module ngx_http_access_module Course: NGINX Web Server Deep Dive | Linux Academy LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive Blocking Access by IP with NGINX Lesson Objectives Explore the ngx_http_access_module in NGINXallow directive deny directiveRestrict Access By IP Address The ngx_http_access_module allows limiting access to certain client addresses. Rules are checked in order until the first match is found. The allow and deny directives can be used within the http, server, location, and limit_except directives:

location / {
    deny  192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny  all;
}

Creating SSL Certificates Using OpenSSL

00:03:59

Lesson Description:

In this lesson, we will learn how to create a self-signed SSL certificate using OpenSSL. LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive Creating SSL Certificates Using OpenSSL Lesson ObjectivesCreate a self-signed SSL certificate using OpenSSL Verify our self-signed SSL certificate using OpenSSLCreate a Certificate Authority Private Key and Certificate First, we'll need a place to store our certificates:

mkdir -p /etc/nginx/certificates
cd /etc/nginx/certificates
Generate a private key for the CA:
openssl genrsa 2048 > ca-key.pem
Generate the X509 certificate for the CA:
openssl req -new -x509 -nodes -days 365000 
      -key ca-key.pem -out ca-cert.pem
Create a Private Key and a Self-Signed Certificate for the NGINX Server Generate a private key and create a certificate request for the NGINX server. We will have to answer some questions:
openssl req -newkey rsa:2048 -days 365000 
      -nodes -keyout server-key.pem -out server-req.pem
Next, process the key to remove the passphrase:
openssl rsa -in server-key.pem -out server-key.pem
We should see the following: writing RSA key. Generate a self-signed X509 certificate for the NGINX server from the certificate request:
openssl x509 -req -in server-req.pem -days 365000 
      -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 
      -out server-cert.pem
We need to allow the nginx user access to the certificates. Add 'read' permissions for 'group' and 'other':
chmod 644 *
Verify the Self-Signed Certificate for the NGINX Server Let’s verify that the X509 certificate was correctly generated:
openssl verify -CAfile ca-cert.pem server-cert.pem
We should see the following: server-cert.pem: OK.

NGINX - Securing Virtual Hosts - HTTPS

00:03:55

Lesson Description:

In this lesson, we will examine how we create secure (HTTPS) virtual hosts and configure these to use SSL/TLS. We will convert an HTTP virtual host to HTTPS. When you complete this lesson, you will understand how to use SSL/TLS to secure a virtual host in NGINX. Reference Links Module ngx_http_ssl_module Configuring HTTPS servers Module ngx_http_core_module - listen Course: NGINX Web Server Deep Dive | Linux Academy LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive NGINX - Securing Virtual Hosts - HTTPS Lesson ObjectivesExplore the listen directive Explore the ngx_http_ssl_module and associated directives Secure a virtual host using SSL/TLSSSL/TLS Configuration Examples

server {
    listen              443 ssl;
    server_name         www.example.com;
    ssl_certificate     www.example.com.crt;
    ssl_certificate_key www.example.com.key;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    ...
}
There are many ways you can configure a server with listen: IPv4, IPv6, with or without IP address/port and UNIX sockets.
listen 127.0.0.1;
listen 8000;
listen *:8000;
listen localhost:8000;
listen [::]:8000;
listen unix:/var/run/nginx.sock;
Verify the Self-Signed Certificate for the NGINX Server Verify the X509 server certificate:
openssl verify -CAfile /etc/nginx/ssl/testdomain.local/ca-cert.pem /etc/nginx/ssl/testdomain.local/server-cert.pem
We should see the following: server-cert.pem: OK. Configure the virtual host to use SSL/TLS Change the listen line to 443 ssl and add the ssl_certificate and ssl_certificate_key directives:
server {
        listen 443 ssl;
        root /var/www/html/testdomain.local;
        server_name testdomain.local www.testdomain.local;
        ssl_certificate /etc/nginx/ssl/testdomain.local/server-cert.pem;
        ssl_certificate_key /etc/nginx/ssl/testdomain.local/server-key.pem;
...

Optimizing Your NGINX Configuration

00:17:19

Lesson Description:

In this lesson, we will examine several ways you can optimize the performance of your NGINX installation. We will test tuning and look at the results of the changes we make. Upon completion of this lesson, you will have a solid high-level understanding of how to improve the performance of NGINX via tuning. Reference Links Core functionality - worker_processes Core functionality - worker_connections Module ngx_http_core_module - open_file_cache Module ngx_http_core_module - open_file_cache_valid Module ngx_http_core_module - client_body_buffer_size Module ngx_http_core_module - client_header_buffer_size Module ngx_http_core_module - client_max_body_size Module ngx_http_core_module - large_client_header_buffers Module ngx_http_core_module - keepalive_timeout Module ngx_http_core_module - client_body_timeout Module ngx_http_core_module - client_header_timeout Module ngx_http_core_module - send_timeout Module ngx_http_log_module - access_log Course: NGINX Web Server Deep Dive | Linux Academy LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive Here are the instructions for the demonstration in the lesson. This demonstration was performed on an Ubuntu 18.04 server. Optimizing Your NGINX Configuration Install ApacheBench and perform a baseline load test We're going to become the root user.

sudo su -
Before we start tuning NGINX, we want to get a baseline measurement using ApacheBench. We will need to install apache2-utils first:
apt-get -y install apache2-utils
Now, we can perform a baseline test. We're going to use the Requests per second metric as our measure for these tests:
for i in `seq 1 10` ; do ab -c 1000 -n 100000 http://127.0.0.1/ | grep Requests >> test_worker_processes_auto.txt ; done
Tuning worker_processes The general baseline configuration is set to auto or the number of cores in the system. Let's take a look at the number of cores in our system:
lshw -short -class cpu
The worker_processes setting is in the nginx.conf file. Open the file for editing:
vi /etc/nginx/nginx.conf
We're going to change worker_processes from auto to the number of cores on our system. Save and exit. Restart NGINX:
nginx -t
systemctl restart nginx
Now, we'll run our ApacheBench test again:
for i in `seq 1 10` ; do ab -c 1000 -n 100000 http://127.0.0.1/ | grep Requests >> test_worker_processes_single.txt ; done
Let's change worker_processes from 1x to 2x the number of cores on our system. Save and exit. Restart NGINX:
nginx -t
systemctl restart nginx
Now, we'll run our ApacheBench test again:
for i in `seq 1 10` ; do ab -c 1000 -n 100000 http://127.0.0.1/ | grep Requests >> test_worker_processes_double.txt ; done
Set worker_processes back to auto, save, exit and restart NGINX. Tuning worker_connections The general baseline configuration is set to 768. We want to set this to the value of ulimit -n:
ulimit -n
The worker_connections setting is in the nginx.conf file. Open the file for editing:
vi /etc/nginx/nginx.conf
We're going to change worker_connections from 768 to 1024. Save and exit. Restart NGINX:
nginx -t
systemctl restart nginx
Now, we'll run our ApacheBench test again:
for i in `seq 1 10` ; do ab -c 1000 -n 100000 http://127.0.0.1/ | grep Requests >> test_worker_connections_auto.txt ; done
We're going to change worker_processes from auto to the number of cores on our system. Save and exit. Restart NGINX:
nginx -t
systemctl restart nginx
Now, we'll run our ApacheBench test again:
for i in `seq 1 10` ; do ab -c 1000 -n 100000 http://127.0.0.1/ | grep Requests >> test_worker_connections_single.txt ; done
We're going to change worker_processes from 1x to 2x the number of cores on our system. Save and exit. Restart NGINX:
nginx -t
systemctl restart nginx
Now, we'll run our ApacheBench test again:
for i in `seq 1 10` ; do ab -c 1000 -n 100000 http://127.0.0.1/ | grep Requests >> test_worker_connections_double.txt ; done
We're going to change worker_connections from 1024 to 512. Save and exit. Restart NGINX:
nginx -t
systemctl restart nginx
Now, we'll run our ApacheBench test again:
for i in `seq 1 10` ; do ab -c 1000 -n 100000 http://127.0.0.1/ | grep Requests >> test_worker_connections_512.txt ; done
Leave worker_processes at 2x and worker_connections at 512. Tuning open_file_cache and open_file_cache_valid We're going to see what effect caching some files in memory has, using the open_file_cache and open_file_cache_valid settings:
vi /etc/nginx/nginx.conf
We're going to add the following to the configuration within the http configuration:
        open_file_cache max=2048 inactive=20s;
        open_file_cache_valid 120s;
Save and exit. Restart NGINX:
nginx -t
systemctl restart nginx
Now, we'll run our ApacheBench test again:
for i in `seq 1 10` ; do ab -c 1000 -n 100000 http://127.0.0.1/ | grep Requests >> test_open_file_cache_512.txt ; done
We're going to change worker_connections from 512 to 768. Save and exit. Restart NGINX:
nginx -t
systemctl restart nginx
Now, we'll run our ApacheBench test again:
for i in `seq 1 10` ; do ab -c 1000 -n 100000 http://127.0.0.1/ | grep Requests >> test_open_file_cache_768.txt ; done
Tuning buffer sizes Let's explore the impact of setting some buffer sizes. Add the following lines to nginx.conf:
        client_body_buffer_size 10K;
        client_header_buffer_size 1k;
        client_max_body_size 8m;
        large_client_header_buffers 4 4k;
Save and exit. Restart NGINX:
nginx -t
systemctl restart nginx
Now, we'll run our ApacheBench test again:
for i in `seq 1 10` ; do ab -c 1000 -n 100000 http://127.0.0.1/ | grep Requests >> test_buffers.txt ; done
Tuning timeouts Let's explore the impact of setting some timeouts. Change keepalive_timeout to 15 and add the following lines to nginx.conf:
        client_body_timeout 12;
        client_header_timeout 12;
        send_timeout 10;
Save and exit. Restart NGINX:
nginx -t
systemctl restart nginx
Now, we'll run our ApacheBench test again:
for i in `seq 1 10` ; do ab -c 1000 -n 100000 http://127.0.0.1/ | grep Requests >> test_timeouts.txt ; done
Configuring access_log buffering Let's explore the impact of enabling buffering on the access log. Edit nginx.conf and add combined buffer=16k to the end of the access_log line, right before the ; at the end of the line. Save and exit. Restart NGINX:
nginx -t
systemctl restart nginx
Now, we'll run our ApacheBench test again:
for i in `seq 1 10` ; do ab -c 1000 -n 100000 http://127.0.0.1/ | grep Requests >> test_log_buffers.txt ; done
You can check out your various test results with:
more test_*

Hands-on Labs are real live environments that put you in a real scenario to practice what you have learned without any other extra charge or account to manage.

01:00:00

Hands-on Labs are real live environments that put you in a real scenario to practice what you have learned without any other extra charge or account to manage.

00:45:00

Hands-on Labs are real live environments that put you in a real scenario to practice what you have learned without any other extra charge or account to manage.

00:45:00

NGINX - Configuring and Customizing Log Files

NGINX - Configuring / Customizing Logging

00:06:30

Lesson Description:

Even though logging is configured by default in NGINX, when managing a web environment with many virtual hosts, load balancers, and more, the default logging configuration is not going to cut it. We will examine how to set logging locations, formats, verbostiy, and more. When you finish this lesson, you should have a solid understanding of how to configure your NGINX logs to you liking. Reference Links Module ngx_http_log_module Core functionality - error_log Module ngx_http_log_module - access_log Logging to syslog Course: NGINX Web Server Deep Dive | Linux Academy LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive NGINX - Configuring / Customizing Logging Lesson Objectives Learn about logs in NGINXAccess log Error log Logging defaults Learn how to customize logging in NGINX Learn about logging using syslogLogs - NGINX Defaults There are two types of logs in NGINX:Access logs Error logsDefault log location is in /var/log/nginx. Default access_log format is combined:

log_format combined '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent"';
Default error_log level is error. Default log configuration in /etc/nginx/nginx.conf. Error LogsTrack application/server errors Adjust logging level for more or less detail: More detail = larger log size Plan carefully, rotate/compress often!Error Log Levels LOW --> HIGH debug - Debugging messages info - Informational messages notice - Notices warn - Warnings error - Errors while processing a request crit - Critical issues: Requires a prompt action alert - Alerts: Action must be taken immediately emerg - Emergency situation: The system is in an unusable state Each log level includes the levels below it. The default log level is error. Access LogsTrack client requests Customize the log format: Fields OrderLog format is defined here: /etc/nginx/nginx.conf Logging to syslog NGINX supports sending the access and error logs to syslog. server=<address>: Defines the address of a syslog server The address can be specified as a domain name or IP address (with an optional port) or as a UNIX-domain socket path specified after the unix: prefix. If port is not specified, the UDP port 514 is used. If a domain name resolves to several IP addresses, the first resolved address is used. facility=<string>: Sets facility of syslog messages, as defined in RFC 3164 Facility can be one of kern, user, mail, daemon, auth, intern, lpr, news, uucp, clock, authpriv, ftp, ntp, audit, alert, cron, or local0-local7. Default is local7. severity=<string>: Sets severity of syslog messages for access_log, as defined in RFC 3164. Possible values are the same as for the second parameter (level) of the error_log directive. Default is info. NGINX supports sending the access and error logs to syslog. tag=<string> Sets the tag of syslog messages. Default is nginx. nohostname Disables adding the 'hostname' field into the syslog message header (1.9.7).

Hands-on Labs are real live environments that put you in a real scenario to practice what you have learned without any other extra charge or account to manage.

01:00:00

MariaDB Basics

MariaDB - Resources and Documentation

00:04:29

Lesson Description:

In this lesson, we are going to introduce you to the https://mariadb.org, https://mariadb.com/services, and https://dev.mysql.com/doc websites. These websites are a rich resource and will assist you with installing, configuring, and maintaining your MariaDB environment. When this lesson is complete, you should have a better understanding of how these websites can be a fantastic tool for anyone working with MariaDB. Reference Links MariaDB Foundation - MariaDB.org Enterprise Database Services | MariaDB MySQL :: MySQL Documentation LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive MariaDB - Resources and Documentation Lesson Objectives Explore the MariaDB websites:https://mariadb.org Downloads Documentation Knowledge Basehttps://mariadb.com/services Services TrainingExplore the MySQL Documentation ? website:https://dev.mysql.com/doc/

Configuring and Securing MariaDB

00:17:23

Lesson Description:

MariaDB is fast and easy to install and set up, but trading ease at the expense of security is a guaranteed way to end up in the headlines. In this lesson, we will walk through hardening a clean installation of MariaDB. We will secure the installation with the mysql_secure_installion script, configure networking, and configure Data-in-Transit and Data-at-Rest Encryption. Upon completion of this lesson, you will have a solid understanding of how to harden a fresh installation of MariaDB. Reference Links Encryption - MariaDB Knowledge Base Data-in-Transit Encryption - MariaDB Knowledge Base Securing Connections for Client and Server - MariaDB Knowledge Base Certificate Creation with OpenSSL - MariaDB Knowledge Base File Key Management Encryption Plugin - MariaDB Knowledge Base LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive Configuring and Securing MariaDB Lesson ObjectivesSecure the default MariaDB installation using the mysql_secure_installation script Configure the network and the second port Configure firewall for MariaDB Configure Data-in-Transit Encryption Configure Data-at-Rest EncryptionDefault InstallationNo root (database) password May have anonymous users Remote root (database) login enabled Has a test database that most people don't useMariaDB provides a guide for securing MariaDB: Securing MariaDB - MariaDB Knowledge Base The mysql_secure_installation scriptSets root (database) password Removes anonymous users Disables remote root (database) login Removes the test database that most people don't useExecute the script:

mysql_secure_installation
Configuring the "extra port" and network In order to make MariaDB available outside of the localhost (127.0.0.1), we need to set the bind-address variable in the /etc/mysql/mariadb.conf.d/50-server.cnf file:
vi /etc/mysql/mariadb.conf.d/50-server.cnf
Change the following line from 127.0.0.1 to the private network address of your server:
bind-address            = 10.0.1.223
We'd also like to configure an *"extra port"* so we can access the server for administrative connections. This is primarily intended for situations where all threads in the thread pool are blocked, and we still need a way to access the server. However, it can also be used to ensure that monitoring systems always have access to the system, even when all connections on the main port are used. Add the following lines in the [mariadb] section in ``/etc/mysql/mariadb.conf.d/50-server.cnf`:
[mariadb]
# Second Admin Port
extra_port = 8385
extra_max_connections = 10
Save the configuration file, then restart the mariadb service using systemctl:
systemctl restart mariadb
Check the status of the mariadb service:
systemctl status mariadb
The mariadb service should be 'enabled' and 'active':
netstat -anp | egrep "3306|8385"
You should see the mariadb service listening on both ports 3306 and 8385, on the private IP address of the server. Configuring the Firewall to Support MariaDB Check the initial status of the firewall:
ufw status
Open ports 3306 and 8385 to allow inbound MariaDB traffic:
ufw allow 3306
ufw allow 8385
Recheck the status of the firewall:
ufw status
Create a Certificate Authority Private Key and Certificate Create a Private Key for the CA:
openssl genrsa 2048 > ca-key.pem
Generate a X509 Certificate for the CA:
openssl req -new -x509 -nodes -days 365000 
      -key ca-key.pem -out ca-cert.pem
Create a Private Key and a Self-Signed Certificate for the MariaDB Server Create a Private Key and CA request:
openssl req -newkey rsa:2048 -days 365000 
      -nodes -keyout server-key.pem -out server-req.pem
Process the key to remove the passphrase:
openssl rsa -in server-key.pem -out server-key.pem
Generate a self-signed X509 certificate:
openssl x509 -req -in server-req.pem -days 365000 
      -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 
      -out server-cert.pem
Create a Private Key and a Self-Signed Certificate for the MariaDB Client Create a Private Key and CA request:
openssl req -newkey rsa:2048 -days 365000 
      -nodes -keyout client-key.pem -out client-req.pem
Process the key to remove the passphrase:
openssl rsa -in client-key.pem -out client-key.pem
Generate a self-signed X509 certificate:
openssl x509 -req -in client-req.pem -days 365000 
      -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 
      -out client-cert.pem
Enable TLS for the MariaDB Server Edit the server configuration file:
vi /etc/mysql/mariadb.conf.d/50-server.cnf
Add the following to the [mariadb] configuration block:
# SSL Configuration
ssl_cert = /etc/mysql/certificates/server-cert.pem
ssl_key = /etc/mysql/certificates/server-key.pem
ssl_ca = /etc/mysql/certificates/ca-cert.pem
Enable TLS for the MariaDB Client Edit the client configuration file:
vi /etc/mysql/mariadb.conf.d/50-client.cnf
Add the following to the [client-mariadb] configuration block:
# SSL Configuration
ssl_cert = /etc/mysql/certificates/client-cert.pem
ssl_key = /etc/mysql/certificates/client-key.pem
ssl_ca = /etc/mysql/certificates/ca-cert.pem
Restart the MariaDB server:
systemctl restart mariadb
Check that TLS is enabled on the MariaDB server Check SSL/TLS settings via the MariaDB client:
mysql -u root -p
SHOW VARIABLES LIKE 'have_ssl';
SHOW SESSION STATUS LIKE 'Ssl_cipher';
SHOW VARIABLES LIKE '%ssl%';
Check SSL/TLS settings using OpenSSL:
openssl s_client -connect <<YOUR_PRIVATE_IP>>:3306 -tls1
Configuring Data-at-Rest Encryption Create the Encryption Key File:
mkdir -p /etc/mysql/encryption
cd /etc/mysql/encryption
for i in `seq 1 10` ; do echo $i";"`openssl rand -hex 32` >> /etc/mysql/encryption/keyfile ; done
Encrypt the Encryption Key File:
openssl rand -hex 128 > /etc/mysql/encryption/keyfile.key
openssl enc -aes-256-cbc -md sha1 
   -pass file:/etc/mysql/encryption/keyfile.key 
   -in /etc/mysql/encryption/keyfile 
   -out /etc/mysql/encryption/keyfile.enc
Configuring MariaDB to Use the Encrypted Key File: Edit the MariaDB server configuration file:
vi /etc/mysql/mariadb.conf.d/50-server.cnf
Add the following to the [mariadb] configuration block, then restart the MariaDB server:
# Encryption at Rest
plugin-load-add=file_key_management
loose_file_key_management_filename = /etc/mysql/encryption/keyfile.enc
loose_file_key_management_filekey = FILE:/etc/mysql/encryption/keyfile.key
loose_file_key_management_encryption_algorithm = AES_CTR
innodb-encrypt-tables
innodb-encrypt-log
innodb-encryption-threads = 4
innodb-tablespaces-encryption
innodb_default_encryption_key_id=7
Validate Encryption is Working, Create an Encrypted Database Table
mysql -u root -p
CREATE DATABASE encryption_test;
USE encryption_test;
CREATE TABLE tab1 (
   id int PRIMARY KEY,
   str varchar(50)
);
SELECT NAME, ENCRYPTION_SCHEME, CURRENT_KEY_ID FROM information_schema.INNODB_TABLESPACES_ENCRYPTION WHERE NAME='encryption_test/tab1';
Create an Unencrypted Database Table
CREATE TABLE tab2 (
   id int PRIMARY KEY,
   str varchar(50)
) ENCRYPTED=NO;
SELECT NAME, ENCRYPTION_SCHEME, CURRENT_KEY_ID FROM information_schema.INNODB_TABLESPACES_ENCRYPTION WHERE NAME='encryption_test/tab2';
Force Encryption on the DB
SET GLOBAL innodb_encrypt_tables='FORCE';
SHOW VARIABLES LIKE '%innodb%';
SHOW VARIABLES LIKE '%innodb_enc%';
CREATE TABLE tab3 (
   id int PRIMARY KEY,
   str varchar(50)
) ENCRYPTED=NO;
SELECT NAME, ENCRYPTION_SCHEME, CURRENT_KEY_ID FROM information_schema.INNODB_TABLESPACES_ENCRYPTION WHERE NAME='encryption_test/tab3';

Hands-on Labs are real live environments that put you in a real scenario to practice what you have learned without any other extra charge or account to manage.

01:00:00

Working With PHP on the LEMP Stack

PHP - Resources and Documentation

00:01:25

Lesson Description:

In this lesson, we are going to introduce you to the php.net website. The website is a rich resource and will assist you with installing, configuring, and maintaining your PHP environment. When this lesson is complete, you should have a better understanding of how the php.net website can be a fantastic tool for anyone working with PHP and the LEMP Stack. Reference Links PHP: Hypertext Preprocessor LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive PHP - Resources and Documentation Lesson Objectives Explore the PHP Websitehttps://php.net Documentation Downloads News

PHP - An Introduction

00:03:35

Lesson Description:

What is PHP and how does it work in the LEMP stack? In this lesson, we will examine how PHP is processed in the LEMP stack, and we'll break down some simple PHP code examples with a demonstration. Upon completion of the lesson, you should have a good high-level understanding of how PHP works in the LEMP stack. Reference Links PHP: What can PHP do? - Manual LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive PHP - An Introduction Lesson ObjectivesLearn how PHP and PHP-FPM fit into the LEMP Stack Look at some example PHP codeWhat is the LEMP Stack?Linux NGINX (eNGINeX - the "E") MariaDB PHPPHP Example - Basic

<html>
 <head>
  <title>PHP Test Page</title>
 </head>
 <body>
 <?php echo '<p>This is a PHP Test Page!</p>'; ?>
 </body>
</html>
PHP Example - Comments
<html>
 <head>
  <title>PHP Test Page</title>
 </head>
 <body>
 <?php
 // Here is a commment
 // Here is another comment
 # This is also a comment
 # Comments are fantastic!
 echo '<p>This is a PHP Test Page!</p>';
 ?>
 </body>
</html>
PHP Example - Variables
<html>
 <head>
  <title>PHP Test Page</title>
 </head>
 <body>
 <?php
 // Let's try some variables!
 $language = 'PHP';
 echo "This is a $language Test Page!<br>";
 echo "We love to program in $language!<br>";
 ?>
 </body>
</html>

Installing and Configuring PHP-FPM

00:06:58

Lesson Description:

In order to properly process PHP pages with NGINX, we need two things: PHP-FPM must be installed, configured, and running, and NGINX must be configured to send PHP pages to PHP-FPM. In this lesson, we will show you how to do both. Upon completion of this lesson, you will be able to install PHP-FPM and configure it with NGINX to properly process your PHP pages. Reference Links PHP: FastCGI Process Manager (FPM) - Manual If you'd like to try this with Apache, check out this lab: Hands-On Lab - Implement an Apache Web Server with PHP Enabled LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive Installing and Configuring php-fpm Lesson ObjectivesLearn about the php-fpm service Explore how php-fpm is configured Install php-fpm on an Ubuntu Linux server Configure NGINX to send PHP pages to php-fpm for processing Test serving some PHP pages using NGINX and php-fpmWhat is PHP-FPM? FPM (FastCGI Process Manager) is an alternative PHP FastCGI implementation with some additional features (mostly) useful for heavy-loaded sites. Install PHP-FPM The php-fpm service can be installed from the default repositories of most major Linux distributions:

apt-get -y install php-fpm
systemctl status php7.2-fpm.service
Configuring PHP-FPM Main file:/etc/php/7.2/fpm/php-fpm.confModules:/etc/php/7.2/fpm/pool.d/*.confConfiguring NGINX to use PHP-FPM With php-fpm now listening on a UNIX socket, we need to configure NGINX to send PHP files to it:
vi /etc/nginx/conf.d/default.conf
 location ~ .php$ {
     fastcgi_pass unix:/run/php/php7.2-fpm.sock;
     fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
     include fastcgi_params;
     include snippets/fastcgi-php.conf;
 }
Testing PHP-FPM Two PHP files on the server:/usr/share/nginx/html/info.php /usr/share/nginx/html/hello.phpWe'll access these via NGINX before and after a reload to see how they are handled:
curl http://`cat /tmp/public_dns.txt`/hello.php
curl http://`cat /tmp/public_dns.txt`/info.php

Hands-on Labs are real live environments that put you in a real scenario to practice what you have learned without any other extra charge or account to manage.

00:30:00

Hands-on Labs are real live environments that put you in a real scenario to practice what you have learned without any other extra charge or account to manage.

01:00:00

Final Words

LEMP - A Review

00:02:37

Lesson Description:

In this lesson we will review the concepts we learned in the LEMP Stack Deep Dive course. LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive Ratings and Feedback Throughout the course, in the lessons and labs, as well as for the entire course itself, are opportunities to provide feedback (thumbs up, thumbs down). I appreciate your feedback as it not only helps me make this course better, but future courses as well. If you liked the lesson / lab / course and would like to make a suggestion, but want to also give it a "thumbs up" you can do that as well! Flash Cards Feel free to check out the Flash Cards for the course to test your knowledge! They are accessible from the main course page as well as in the upper right-hand corner of the lesson pages. Linux Academy Community Another resource to assist you in your learning adventure is the Linux Academy Community. You can access Community via the upper navigation bar. LEMP - A Review NGINXHTTP/S web server Built for performance Low memory overheadLoad-balancing functionality Proxying / caching functionality Many advanced features Included in the standard repositories for many Linux distributions Growing market shareMariaDBMariaDB was created as a response to Oracle's acquisition of Sun Microsystems, and MySQL AG, in 2010. MariaDB is fully open-source. MariaDB is a "drop-in binary replacement" for MySQL. There are some feature differences. Commercial support is available for MariaDB.PHPRecursive acronym for PHP: Hypertext Preprocessor A widely-used open source general-purpose scripting language Especially suited for web development Can be embedded into HTML Is executed on the server side, returns HTML: Code is hidden from the clientI hope you enjoyed the course! Keep on learning, and best of luck with your journey!

LEMP - More Resources on Linux Academy

00:02:08

Lesson Description:

In this lesson, we will review other Linux Academy resources that are available to you, if you would like to continue your LEMP journey. Reference Links Course: NGINX Web Server Deep Dive | Linux Academy Course: Apache Web Server Hardening | Linux Academy Hands-On Lab - Working with MySQL/MariaDB Course: Database Administration and SQL Language Basics | Linux Academy LEMP Stack Deep Dive Git Repository Feel free to explore the configurations and code from the course at: GitHub - linuxacademy/content-lemp-deep-dive LEMP - More Resources on Linux Academy NGINX Web Server Deep Dive By the time you've finished this course you will be able to:Read, write, and understand NGINX configuration Utilize NGINX as a web server, reverse proxy, and load balancer Build and install multiple dynamic modules to add features to NGINX Improve the performance of NGINX beyond the default configurationApache Web Server Hardening This course covers securing the Apache web server:Securing an Apache web server Configuring a Linux firewall CentOS 7 SELinuxWorking with MySQL/MariaDB In this hands-on lab, you will install MySQL/MariaDB on a CentOS 7 server. Once that is complete, you will be required to configure the server with the provided data. Database Administration and SQL Language Basics In this course, we will be using MySQL to learn about administering a database, as well as the basics of the SQL language.The first half of the course begins with the installation of a MySQL server, then covers common administrative tasks. The second half of the course focuses on how to use the SQL language in order to view and manipulate data.There is much more content available - search the Linux Academy website! Keep on learning, and best of luck with your journey!

Take this course and learn a new skill today.

Transform your learning with our all access plan.

Start 7-Day Free Trial