How to Install LEMP Stack On Ubuntu 20.04
Introduction
The LEMP software stack is a group of software that can be used to serve dynamic web pages and web applications written in PHP. The term LEMP is an acronym that represents Linux operating system, Nginx (pronounced engine-x, hence the E in the acronym) web server, MySQL database, and PHP.
This guide demonstrates how to install a LEMP stack on an Ubuntu 20.04 server. The Ubuntu operating system takes care of the first requirement. We will describe how to get the rest of the components up and running.
Prerequisites
To complete this tutorial, you will need access to an Ubuntu 20.04 server as a regular, non-root sudo user, and a firewall enabled on your server.
To display web pages to our site visitors, we are going to employ Nginx, a high-performance web server.
You have Nginx installed to serve your content. Now you can install PHP to process code and generate dynamic content for the web server.
Nginx requires an external program to handle PHP processing and act as a bridge between the PHP interpreter itself and the web server. This allows for better overall performance in most PHP-based websites, but it requires additional configuration. You’ll need to install php-fpm, which stands for “PHP FastCGI process manager”, and tell Nginx to pass PHP requests to this software for processing. Additionally, you’ll need php-mysql, a PHP module that allows PHP to communicate with MySQL-based databases. Core PHP packages will automatically be installed as dependencies.
3 Installing MySQL
Now that you have a web server up and running, you need to install the database system to be able to store and manage data for your site. MySQL is a popular database management system used within PHP environments.
Again, use apt to acquire and install this software:
$sudo apt install mysql-server
When prompted, confirm installation by typing Y, and then ENTER.
When the installation is finished, it’s recommended that you run a security script that comes pre-installed with MySQL. This script will remove some insecure default settings and lock down access to your database system. Start the interactive script by running:
sudo mysql_secure_installation
This will ask if you want to configure the VALIDATE PASSWORD PLUGIN.
Note: Enabling this feature is something of a judgment call. If enabled, passwords that don’t match the specified criteria will be rejected by MySQL with an error. It is safe to leave validation disabled, but you should always use strong, unique passwords for database credentials.
When you’re finished, test if you’re able to log in to the MySQL console by typing:
$ sudo mysql
This will connect to the MySQL server as the administrative database user root, which is inferred by the use of sudo when running this command. You should see output like this:
To exit the MySQL console, type:
mysql> exit
Note: you didn’t need to provide a password to connect as the root user, even though you have defined one when running the mysql_secure_installation script. That is because the default authentication method for the administrative MySQL user is unix_socket instead of a password.
For increased security, it’s best to set up dedicated user accounts with less expansive privileges for every database, especially if you plan on having multiple databases hosted on your server.
4 Configuring Nginx to Use the PHP Processor
When using the Nginx web server, we can create server blocks (similar to virtual hosts in Apache) to encapsulate configuration details and host more than one domain on a single server. Here, we’ll use your_domain as an example domain name.
On Ubuntu 20.04, Nginx has one server block enabled by default and is configured to serve documents out of a directory at /var/www/html. While this works well for a single site, it can become difficult to manage if you are hosting multiple sites. Instead of modifying /var/www/html, we’ll create a directory structure within /var/www for the your_domain website, leaving /var/www/html in place as the default directory to be served if a client request doesn’t match any of other sites.
Create the root web directory for your_domain as follows:
$ sudo mkdir /var/www/your_domain
Next, assign ownership of the directory with the $USER environment variable, which will reference your current system user:
$ sudo chown -R $USER:$USER /var/www/your_domain
Then, open a new configuration file in Nginx’s sites-available directory using your preferred command-line editor. Here, we’ll use nano:
$ sudo nano /etc/nginx/sites-available/your_domain
This will create a new blank file. Paste in the following bare-bones configuration:
/etc/nginx/sites-available/your_domain
server {
listen 80;
server_name your_domain www.your_domain;
root /var/www/your_domain;
index index.html index.htm index.php;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
location ~ /\.htaccess {
deny all;
}
}
When you’re done editing, save and close the file. If you’re using nano, you can do so by typing CTRL+X and then y and ENTER to confirm.
Activate your configuration by linking to the config file from Nginx’s sites-enabled directory:
$ sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/
Then, unlink the default configuration file from the /sites-enabled/ directory:
$ sudo unlink /etc/nginx/sites-enabled/default
Note: If you ever need to restore the default configuration, you can do so by recreating the symbolic link, like this:
$ sudo ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/
This will tell Nginx to use the configuration the next time it is reloaded. You can test your configuration for syntax errors by typing:
sudo nginx -t
If any errors are reported, go back to your configuration file to review its contents before continuing.
When you are ready, reload Nginx to apply the changes:
sudo systemctl reload nginx
Your new website is now active, but the web root /var/www/your_domain is still empty. Create an index.html file in that location so that we can test that your new server block works as expected:
nano /var/www/your_domain/index.html
Include the following content in this file:
/var/www/your_domain/index.html
<html>
<head>
<title>your_domain website</title>
</head>
<body>
<h1>Hello World!</h1>
<p>This is the landing page of <strong>your_domain</strong>.</p>
</body>
</html>
Now go to your browser and access your server’s domain name or IP address, as listed within the server_name directive in your server block configuration file:
http://server_domain_or_IP
You’ll see a page like this:
If you see this page, it means your Nginx server block is working as expected.
You can leave this file in place as a temporary landing page for your application until you set up an index.php file to replace it. Once you do that, remember to remove or rename the index.html file from your document root, as it would take precedence over an index.php file by default.
Your LEMP stack is now fully configured. In the next step, we’ll create a PHP script to test that Nginx can handle .php files within your newly configured website.
5 Testing PHP with Nginx
Your LEMP stack should now be ready. You can test it to validate that Nginx can correctly hand .php files off to your PHP processor.
You can complete this by creating a test PHP file in your document root. Open a new file called info.php within your document root in your text editor:
$ nano /var/www/your_domain/info.php
Type or paste the following lines into the new file. This is valid PHP code that will return information about your server:
/var/www/your_domain/info.php
When you are finished, save and close the file by typing CTRL+X and then y and ENTER to confirm.
You can now access this page in your web browser by visiting the domain name or public IP address you’ve set up in your Nginx configuration file, followed by /info.php:
http://server_domain_or_IP/info.php
You will see a web page containing detailed information about your server:
After checking the relevant information about your PHP server through that page, it’s best to remove the file you created as it contains sensitive information about your PHP environment and your Ubuntu server. You can use rm to remove that file:
sudo rm /var/www/your_domain/info.php
You can always regenerate this file if you need it later.
6 Testing Database Connection from PHP (Optional)
If you want to test whether PHP is able to connect to MySQL and execute database queries, you can create a test table with dummy data and query for its contents from a PHP script. Before that, we need to create a test database and a new MySQL user.
We’ll create a database named example_database and a user named example_user, but you can replace these names with different values.
First, connect to the MySQL console using the root account:
$ sudo mysql
To create a new database, run the following command from your MySQL console:
mysql> CREATE DATABASE example_database;
Now you can create a new user and grant them full privileges on the custom database you’ve just created.
The following command creates a new user named example_user, using mysql_native_password as the default authentication method. We’re defining this user’s password as "password", but you should replace this value with a secure password of your own choosing.
mysql> CREATE USER'example_user'@'%' IDENTIFIED WITH mysql_native_password BY 'password';
Now we need to give this user permission over the example_database database:
mysql> GRANT ALL ON example_database.* TO 'example_user'@'%';
This will give the example_user user full privileges over the example_database database while preventing this user from creating or modifying other databases on your server.
Now exit the MySQL shell with:
mysql> exit
You can test if the new user has the proper permissions by logging in to the MySQL console again, this time using the custom user credentials:
mysql -u example_user -p
Please notice that the -p flag in this command will prompt you for the password used when creating the example_user user. After logging in to the MySQL console, confirm that you have access to the example_database database:
mysql> SHOW DATABASES;
This will give you the following output:
Output
+--------------------+
| Database |
+--------------------+
| example_database |
| information_schema |
+--------------------+
2 rows in set (0.000 sec)
Next, we’ll create a test table named quote_list. From the MySQL console, run the following statement:
CREATE TABLE example_database.quote_list(
item_id INT AUTO_INCREMENT,
content VARCHAR(255),
PRIMARY KEY(item_id)
);
Insert a few rows of content in the test table. You might want to repeat the next command a few times, using different values:
mysql> INSERT INTO example_database.quote_list(content) VALUES ("It always seems impossible until it's done.");
To confirm that the data was successfully saved to your table, run:
SELECT * FROM example_database.quote_list;
You’ll see the following output:
After confirming that you have valid data in your test table, you can exit the MySQL console:
mysql> exit
Now you can create the PHP script that will connect to MySQL and query for your content. Create a new PHP file in your custom web root directory using your preferred editor. We’ll use nano for that:
$ nano /var/www/your_domain/quote_list.php
The following PHP script connects to the MySQL database and queries for the content of the quote_list table, exhibiting the results in a list. If there’s a problem with the database connection, it will throw an exception. Copy this content into your quote_list.php script:
/var/www/your_domain/quote_list.php
<?php
$user = "example_user";
$password = "password";
$database = "example_database";
$table = "quote_list";
try {
$db = new PDO("mysql:host=localhost;dbname=$database", $user, $password);
echo "<h2>TODO</h2><ol>";
foreach($db->query("SELECT content FROM $table") as $row) {
echo "<li>" . $row['content'] . "</li>";
}
echo "</ol>";
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
Save and close the file when you’re done editing.
You can now access this page in your web browser by visiting the domain name or public IP address configured for your website, followed by /quote_list.php:
http://server_domain_or_IP/quote_list.php
You should see a page like this, showing the content you’ve inserted in your test table:
That means your PHP environment is ready to connect and interact with your MySQL server.
Conclusion
In this guide, we’ve built a flexible foundation for serving PHP websites and applications to your visitors, using Nginx as the web server and MySQL as the database system.