How To Install LINUX,NGINX,MySQL,PHP(LEMP stack) on Ubuntu 20.04
Introduction
The LEMP software stack is a collection of programs that can be used to deliver PHP-based dynamic web pages and web applications. This is an acronym for a Linux operating system with a web server called Nginx (pronounced "Engine-X"). The backend data is saved in a MySQL database, and PHP handles the dynamic processing.
Installing an LEMP stack on an Ubuntu 20.04 server is demonstrated in this guide. The first criteria is met by the Ubuntu operating system. We'll go over how to set up and run the remaining components.
Prerequisites
You'll need access to an Ubuntu 20.04 server as a regular, non-root sudo user and a firewall enabled on your server to finish this guide. Follow our introductory server setup instructions for Ubuntu 20.04 to get started.
1 – Installing the Nginx Web Server
In order to display web pages to our site visitors, we are going to employ Nginx, a high-performance web server. We’ll use the apt package manager to obtain this software.
Since this is our first time using apt for this session, start off by updating your server’s package index. Following that, you can use apt install to get Nginx installed:
sudo apt update
sudo apt install nginx
When prompted, enter Y to confirm that you want to install Nginx. Once the installation is finished, the Nginx web server will be active and running on your Ubuntu 20.04 server.
If you have the ufw firewall enabled, as recommended in our initial server setup guide, you will need to allow connections to Nginx. Nginx registers a few different UFW application profiles upon installation. To check which UFW profiles are available, run:
sudo ufw app list
Available applications:
Nginx Full
Nginx HTTP
Nginx HTTPS
OpenSSH
It is recommended that you enable the most restrictive profile that will still allow the traffic you need. Since you haven’t configured SSL for your server in this guide, you will only need to allow regular HTTP traffic on port 80.
Enable this by typing:
sudo ufw allow 'Nginx HTTP'
You can verify the change by running:
sudo ufw status
This command’s output will show that HTTP traffic is now allowed:
Status: active
To Action From
-- ------ ----
OpenSSH ALLOW Anywhere
Nginx HTTP ALLOW Anywhere
OpenSSH (v6) ALLOW Anywhere (v6)
Nginx HTTP (v6) ALLOW Anywhere (v6)
With the new firewall rule added, you can test if the server is up and running by accessing your server’s domain name or public IP address in your web browser.
If you do not have a domain name pointed at your server and you do not know your server’s public IP address, you can find it by running the following command:
ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'
Copy
This will print out a few IP addresses. You can try each of them in turn in your web browser.
As an alternative, you can check which IP address is accessible, as viewed from other locations on the internet:
curl -4 icanhazip.com
Copy
Type the address that you receive in your web browser and it will take you to Nginx’s default landing page:
http://server_domain_or_IP
If you see this page, it means you have successfully installed Nginx and enabled HTTP traffic for your web server.
2 — Installing MySQL
After you've set up a web server, you'll need to set up a database system so that you can store and manage data for your website. MySQL is a well-known database management system that is commonly used in PHP contexts.
To get and install this package, use apt once more
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 which 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.
Answer Y for yes, or anything else to continue without enabling.
VALIDATE PASSWORD PLUGIN can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD plugin?
Press y|Y for Yes, any other key for No:
If you answer “yes”, you’ll be asked to select a level of password validation. Keep in mind that if you enter 2 for the strongest level, you will receive errors when attempting to set any password which does not contain numbers, upper and lowercase letters, and special characters, or which is based on common dictionary words.
There are three levels of password validation policy:
LOW Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary file
Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 1
Regardless of whether you chose to set up the VALIDATE PASSWORD PLUGIN, your server will next ask you to select and confirm a password for the MySQL root user. This is not to be confused with the system root. The database root user is an administrative user with full privileges over the database system. Even though the default authentication method for the MySQL root user dispenses the use of a password, even when one is set, you should define a strong password here as an additional safety measure. We’ll talk about this in a moment.
If you enabled password validation, you’ll be shown the password strength for the root password you just entered and your server will ask if you want to continue with that password. If you are happy with your current password, enter Y for “yes” at the prompt:
Estimated strength of the password: 100
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y
For the rest of the questions, press Y and hit the ENTER key at each prompt. This will remove some anonymous users and the test database, disable remote root logins, and load these new rules so that MySQL immediately respects the changes you have made.
When you’re finished, test if you’re able to log in to the MySQL console by typing:
- sudo mysql
Copy
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:
Output
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 22
Server version: 8.0.19-0ubuntu5 (Ubuntu)
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
To exit the MySQL console, type:
- mysql > exit
Even though you created a password when running the mysql secure installation script, you didn't need to supply one to join as the root user. Because the administrative MySQL user's default authentication mechanism is unix socket rather than password, this is the case. Although this may appear to be a security risk at first glance, it really strengthens the database server's security because the only users who can log in as the root MySQL user are system users with sudo rights connecting through the console or through an application with the same capabilities. In practice, this means you won't be able to connect from your PHP application using the administrative database root user. If the default authentication method is changed from unix socket to password, setting a password for the root MySQL account serves as a protection.
It's recommended to set up dedicated user accounts with fewer privileges for each database, especially if you plan on hosting numerous databases on your server, for added protection.
Note: At the time of this writing, the native MySQL PHP library mysqlnd doesn’t support caching_sha2_authentication, the default authentication method for MySQL 8. For that reason, when creating database users for PHP applications on MySQL 8, you’ll need to make sure they’re configured to use mysql_native_password instead. We’ll demonstrate how to do that in Step 6.
Your MySQL server is now installed and secured. Next, we’ll install PHP, the final component in the LEMP stack.
3 – Installing PHP:
You've set up Nginx to deliver your content, and MySQL to store and manage your data. PHP can now be installed on the web server to execute code and generate dynamic content.
Nginx requires a separate application to handle PHP processing and function as a bridge between the PHP interpreter and the web server, whereas Apache embeds the PHP interpreter in each request. Most PHP-based websites will benefit from this, although it will necessitate additional setting. Install php-fpm, which stands for "PHP fastCGI process manager," then instruct Nginx to send PHP requests to it for processing. You'll also require, php-mysql a PHP module that enables PHP to interface with MySQL databases.
To install the php-fpm and php-mysql packages, run:
sudo apt install php-fpm php-mysql
When prompted, type Y and ENTER to confirm installation.
You now have your PHP components installed. Next, you’ll configure Nginx to use them.
Regardless of whether you used the VALIDATE PASSWORD PLUGIN or not, your server will prompt you to choose and confirm a password for the MySQL root user. This is not to be confused with the root of the operating system. The database root user is a database administrator who has full control over the database system. Even though the MySQL root user's default authentication mechanism does not need the usage of a password, you should establish a strong password here as an added safety measure. We'll get to that in a minute.
4 – Configuring Nginx to use the PHP Processor:
Configuring Nginx to Use the PHP Processor
We can establish server blocks (similar to virtual hosts in Apache) to encapsulate configuration details and host several domains on a single server when using the Nginx web server. We'll use your domain as an example domain name in this article. See our introduction to Listed Hosting DNS for more information on how to set up a domain name with Listed Hosting.
Nginx is configured to serve documents from a directory at /var/www/html on Ubuntu 20.04. Nginx has one server block enabled by default and is configured to serve documents from a directory at /var/www/html. While this works well for a single site, it might be challenging to maintain if you have numerous sites to handle. We'll construct a directory structure within /var/www for the your domain website instead of changing /var/www/html, leaving /var/www/html as the default directory to be served if a client request doesn't match any other sites.Make the following changes to your domain's root web directory:
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
Copy
This will create a new blank file. Paste in the following bare-bones configuration:
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 ~ /\.ht {
deny all;
}
}
The following are the functions of each of these directives and location blocks:
*listen — Specifies the port on which Nginx will listen. In this scenario, it will listen on port 80, which is the standard HTTP port.
*root — Defines the document root, which is where this website's files are stored.
*index — This parameter specifies the order in which Nginx will prioritize index files for this website. To allow for quick setup of a maintenance landing page in PHP projects, it is usual practice to list index.html files with a higher precedence than index.php files. These options can be tweaked to better suit your application's requirements.
*server name — Specifies the domain names and/or IP addresses for which this server block shall answer. Set this directive to the domain name or public IP address of your server.
*location / — The try files directive in the first location block looks for the existence of files or folders that match a URI request. If Nginx is unable to locate the requested resource, it will return a 404 error.
.php$ —.php$ —.php$ —.php$ —.php By referring Nginx to the fastcgi-php.conf configuration file and the php7.4-fpm.sock file, which indicates what socket is associated with php-fpm, this location block handles the actual PHP processing.
*location /.ht — The final location block is for.htaccess files, which Nginx does not handle. If any.htaccess files get up in the document root as a result of the deny all directive, they will not be delivered to visitors.
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-enable
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 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 view this page, your Nginx server block is functioning properly.
This file can be used as a temporary landing page for your application until an index.php file is created to replace it. After that, remember to delete or rename the index.html file from your document root, as it will automatically take precedence over an index.php file.
Your LEMP stack is now completely set up. We'll construct a PHP script in the next step to ensure that Nginx can handle.php files on your freshly configured website.
5 - Testing PHP with Nginx:
Your LEMP stack should now be fully functional. You may put it to the test to see if Nginx can pass.php files to your PHP processor appropriately.
Create a test PHP file in your document root to accomplish this. In your text editor, create a new file called info.php in your document root:
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
<?php
phpinfo();
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:
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:
You can create a test table with dummy data and query its contents using a PHP script to see if PHP is capable of connecting to MySQL and executing database queries. To accomplish so, we'll need to create a test database and a new MySQL user with the required permissions to access it.
The native MySQL PHP library mysqlnd does not support caching sha2 authentication, the default authentication technique for MySQL 8, as of this writing. To connect to the MySQL database using PHP, we'll need to create a new user with the mysql native password authentication technique.
We'll establish a database called example database and a user called example user, but you can use whatever name you choose.
sudo mysql
To create a new database, run the following command from your MySQL console:
mysql> CREATE DATABASE example_database;
You may now create a new user and give them full access to the custom database you just made.
The following command creates a new user named example user with the default authentication method of mysql native password. This user's password is set to password, but you should change it to a strong 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:
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:
exit
Copy
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
Notice the -p flag in this command, which 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:
+--------------------+
| Database |
+--------------------+
| example_database |
| information_schema |
+--------------------+
2 rows in set (0.000 sec)
2 rows in set (0.000 sec)
Next, we’ll create a test table named todo_list. From the MySQL console, run the following statement:
- CREATE TABLE example_database.todo_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:
- INSERT INTO example_database.todo_list (content) VALUES ("My first important item");
To confirm that the data was successfully saved to your table, run:
-
You’ll see the following output:
Output+---------+--------------------------+ | item_id | content | +---------+--------------------------+ | 1 | My first important item | | 2 | My second important item | | 3 | My third important item | | 4 | and this one more thing | +---------+--------------------------+ 4 rows in set (0.000 sec)
After confirming that you have valid data in your test table, you can exit the MySQL console:
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:The following PHP script connects to the MySQL database and queries for the content of the todo_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
todo_list.php
script:/var/www/your_domain/todo_list.phpSave 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
/todo_list.php
:http://server_domain_or_IP/todo_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 web server and MySQL as database system.