Advance

How to install LEMP stack on Debian 10

How to install LEMP stack on Debian 10
1
(1)

LEMP is formed by four open-source components that are used to serve dynamic web pages and web applications. LEMP has four Linux operation system abbreviations in it. Respectively, L stands for Linux, E is for Nginx (engine-x), M is for MariaDB or MySQL, and P stands for PHP, Perl, or Python.

You can find that MySQL is available in the LEMP stack as the database management system. But Debian and some other Linux distributions are planned to use MariaDB instead of MySQL. Before all, you need to have your own Linux VPS initially.

 

To let this tutorial work better, please consider the below Prerequisites:

A non-root user with sudo privileges

To set up, follow our Initial Setup with Debian 10.

How to install LEMP stack on Debian 10

Join us to walk through the steps of this guide to show you how to install a LEMP stack on a Debian 10 server using MariaDB as the database management system. You may also be interested in learning How to install LEMP on CentOS 8 OR How to install LAMP on Debian 10.

Recommended Article: Install ClamAV antivirus on CentOS 7

 

Step 1: How To Install The Nginx Web Server

You choose the popular Nginx to serve web pages to your visitors. Like other software in this guide, it comes directly from Debian’s default package repositories. This means you can use the apt package management suite to complete the installation.

If you have not already used apt, you need to start off by updating your local package index. Then install the server:

sudo apt update  sudo apt install nginx

Nginx starts running upon installation, as it is designed in Debian 10. Allow connections to Nginx if the ufw firewall is running. Find the most restrictive profile that will still allow the traffic you want to enable them. Until here, you have not configures SSL for your server, so you need to allow HTTP traffic on port 80.

Enable this using the command below:

sudo ufw allow 'Nginx HTTP'

You can verify the change by typing:

sudo ufw status
Output
Status: active    To                         Action      From  --                         ------      ----  OpenSSH                    ALLOW       Anywhere  Nginx HTTP                 ALLOW       Anywhere  OpenSSH (v6)               ALLOW       Anywhere (v6)  Nginx HTTP (v6)            ALLOW       Anywhere (v6)    

To test whether the server is up and running or not, check it by accessing your server’s domain name or public IP address in your web browser. You may find that you have no domain name pointed at your server and you do not know your server’s public IP address. Here is the solution to find it:

ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'

You use the above command to print out a few IP addresses to try each of them in turn in your web browser. In the following, you can type one of the addresses that you receive in your web browser to let it take you to

Nginx’s default landing page:

http://your_domain_or_IP  

welcome to Nginx page

If you see the above page, you have successfully installed Nginx.

 

 

 

Step 2: How To Install MariaDB

In this step, you should install the database system to be able to store and manage data for your site because you have a web server up and running.

The meta package mysql-server, which was traditionally used to install the MySQL server, was replaced by default-mysql-server in Debian 10.

This metapackage references MariaDB, a community fork of the original MySQL server by Oracle, and it’s currently the default MySQL-compatible database server available on Debian-based package manager repositories.

However, you are recommended to replace the metapackage with installing MariaDB using the program’s actual package, mariadb-server.

Type the following command to install this software:

sudo apt install mariadb-server

You are recommended to run a security script that comes pre-installed with MariaDB after the installation. You can use it to remove some insecure default settings and lock down access to your database system. Start the interactive script by running:

sudo mysql_secure_installation

Use the script to go through a series of prompts where you can make some changes to your MariaDB setup. Be ready for the first prompt which wants you to enter the current database root password. 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. Because you just installed MariaDB and haven’t made any configuration changes yet, this password will be blank, so just press ENTER at the prompt.

Let’s see what would be the next prompt. You will be asked whether if you prefer to set up a database root password. Because MariaDB uses a special authentication method for the root user that is typically safer than using a password, you don’t need to set this now. Type N and then press ENTER. To accept the defaults for all the subsequent questions press Y and then ENTER.

This will remove anonymous users and the test database, disable remote root login, and load these new rules so that MariaDB immediately respects the changes you have made.
When you’re finished, log in to the MariaDB console by typing:

sudo mariadb

This will connect to the MariaDB server as the administrative database user root, which is inferred by the use of sudo when running this command.

Output
Welcome to the MariaDB monitor.  Commands end with ; or \g.  Your MariaDB connection id is 74  Server version: 10.3.15-MariaDB-1 Debian 10    Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.    Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.    MariaDB [(none)]>

Note: You are not forced to provide a password to connect as the root user. It could be possible because the default authentication method for the administrative MariaDB user is unix_socket instead of password. It helps the database server to be more secure as the only users allowed to log in as the root MariaDB user are the system users with sudo privileges connecting from the console or through an application running with the same privileges. Please consider that, in practical terms, that means you won’t be able to use the administrative database root user to connect from your PHP application.

Also, you can dedicate user accounts with less expansive privileges set up for every database to increase security. Recommended when you plan on having multiple databases hosted on your server.

To demonstrate such a setup, we’ll create a database named example_database and a user named example_user, but you can replace these names with different values.

Type the following command from your MariaDB console to create a new database.

MariaDB [(none)]  CREATE DATABASE example_database;

After that, you are ready to create a new user and grant them full privileges on the custom database you’ve just created. To know more about this user’s password as password. But remember to replace this value with a secure password of your own choosing.

MariaDB [(none)]> GRANT ALL ON example_database.* TO 'example_user'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;

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.

And to ensure that they are saved and available in the current session:

MariaDB [(none)]> FLUSH PRIVILEGES;

To exit the MariaDB shell:

MariaDB [(none)]> Exit

Then, to test if the new user has the proper permissions by logging in to the MariaDB console again, this time using the custom user credentials:

mariadb -u example_user -p

Note 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 MariaDB console, confirm that you have access to the example_database database:

MariaDB [(none)]> SHOW DATABASES;
Output
+--------------------+  | Database           |  +--------------------+  | example_database   |  | information_schema |  +--------------------+  2 rows in set (0.000 sec)

To exit the MariaDB shell, type:

MariaDB [(none)]> Exit

At this point, your database system is set up and you can move on to installing PHP, the final component of the LEMP stack.

 

 

 

Step 3: How To Install PHP For Processing

After installing Nginx and MySQL, let’s install PHP to process code and generate dynamic content for the webserver. Nginx requires an external program to handle PHP processing and act as a bridge between the PHP interpreter itself and the webserver while we know the Apache embeds the PHP interpreter in each request. To provide a better performance in most OHP based websites after requiring 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.

Type the following command to install the php-fpm and php-mysql packages:

sudo apt install php-fpm php-mysql

 

 

 

Step 4: How To Configure Nginx To Use The PHP Processor

You can use the server blocks to encapsulate configuration details and host more than one domain on a single server. Notice that we use your_domain as an example domain name.

You can find one server block enabled by default and is configured to serve documents out of a directory at /var/www/html for Nginx in Debian 10. you may see it is difficult to manage if you are hosting multiple sites even it is working well for a single site. Also, you can 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 other sites instead of modifying /var/www/html

Now, create the root web directory for your_domain as follows:

sudo mkdir /var/www/your_domain

Then, assign ownership of the directory with the $USER environment variable, which should 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;      listen [::]:80;        root /var/www/your_domain;      index index.php index.html index.htm;        server_name your_domain;        location / {          try_files $uri $uri/ =404;      }        location ~ \.php$ {          include snippets/fastcgi-php.conf;          fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;      }  }

 

You see a basic configuration that listens on port 80 and serves files from the webroot you just created. It will only respond to requests to the host or IP address provided after server_name, and any files ending in .php will be processed by php-fpm before Nginx sends the results to the user.

When the edit is finished, save, and close the file. If you used nano to create the file, do so by typing CTRL+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/

This will tell Nginx to use the configuration next time it is reloaded. To test your configuration for syntax errors run the following command:

sudo nginx -t

You may face an error. To solve it you can go back to your configuration file to review its contents before continuing.

When you are ready, reload Nginx to make the changes:

sudo systemctl reload nginx

Finally, you will create a file in your new web root directory to test out PHP processing.

 

 

Step 5: How To Create a PHP File to Test Configuration

Till here, you have your LEMP stack that should now be completely set up. You can test it to validate that Nginx can correctly hand .php files off to your PHP processor.

To do this create 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 a valid PHP code that will return information about your server:

/var/www/your_domain/info.php
<?php  phpinfo();  ?>

 

Save and close the file by typing CTRL+X and then y and ENTER to confirm when you finished it.

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://your_domain/info.php

 

You will see a web page containing detailed information about your server:

Php info page

You are recommended to remove the file you created after checking the relevant information about your PHP server through that page as it contains sensitive information about your PHP environment and your Debian server.

Use the command below to do this:

rm /var/www/your_domain/info.php

Once you need it again, you would be able to regenerate the file.

Recommended Article: How to install LEMP stack on Debian 10

 

Step 6: How To Test Database Connection from PHP (Optional)

Create a test table dummy data and query for its contents from a PHP script to help you test that is PHP able to connect to MariaDB and execute database queries or not.

If you agree, the first step is to connect  the MariaDB console with the database user you created in Step 2 of this guide:

mariadb -u example_user -p

Create a table named todo_list. From the MariaDB 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:

MariaDB [(none)]> INSERT INTO example_database.todo_list (content) VALUES ("My first important item");

Then, you need to confirm that you saved data to your table

MariaDB [(none)]> SELECT * FROM example_database.todo_list;
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 MariaDB console:

MariaDB [(none)]> Exit

After this, you can create the PHP script that will connect to MariaDB and query for your content. So, you can create a new PHP file in your custom webroot directory using your preferred editor. We use nano:

nano /var/www/your_domain/todo_list.php

Add the following content to your PHP script:

<?php  $user = "example_user";  $password = "password";  $database = "example_database";  $table = "todo_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 after editing.

It is expected to access this page now in your web browser by visiting the domain name or public IP address you have set up in your Nginx configuration file, followed by /todo_list.php:

http://your_domain/todo_list.php

You should see a page like this, showing the content you have inserted in your test table:

 

To do list page

That means your PHP environment is ready to connect and interact with your MariaDB server.

 

Conclusion

In this article, you learned How to install the LEMP stack on Debian 10. From now on you have a flexible foundation for serving PHP websites and applications to your visitors, using Nginx as a web server. You can handle PHP requests through php-fpm after setting up Nginx and store your website’s data after setting up a MariaDB database. To improve more your current setup, you can install Composer for dependency and package management in PHP, and you can also install an OpenSSL certificate for your website using Let’s Encrypt.

How useful was this post?

Click on a star to rate it!

Average rating 1 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

View More Posts
Tom Veitch
Eldernode Writer
We Are Waiting for your valuable comments and you can be sure that it will be answered in the shortest possible time.

10 thoughts on “How to install LEMP stack on Debian 10

    1. You can download and install all of them together in a package which is named Stack. Using Linux, Apache, MySQL and PHP as your operating system.

    1. – It is about Apache and Nginx. With a LAMP stack the web server used is Apache, whereas with a LEMP stack environment the web server used is Nginx. Both web servers operate differently, and require different configurations to set them up

    1. To create a virtual host configuration file site.eldernode.local.conf in /etc/nginx/conf.d/ directory.

      sudo nano /etc/nginx/conf.d/site.eldernode.local.conf

    1. – As we mentioned in the article, it starts upon installation. But you can also use the following command:
      sudo systemctl start nginx

Leave a Reply

Your email address will not be published. Required fields are marked *

We are by your side every step of the way

Think about developing your online business; We will protect it compassionately

We are by your side every step of the way

+8595670151

7 days a week, 24 hours a day