Back to Blog

How to Install a LEMP Stack on Ubuntu and Debian

How to install a LEMP stack on Ubuntu and Debian: Nginx, MariaDB and PHP-FPM, the server block, the PHP socket, permissions, HTTPS and common errors.

Nodesty Team9 min readServers
The words LEMP Stack with Nginx, MariaDB and PHP on a dark Nodesty background

A LEMP stack is the classic foundation for PHP websites on a Linux server: Linux, Nginx (pronounced "engine-x", hence the E), MariaDB or MySQL, and PHP. WordPress, Laravel and most other PHP applications run on it. Installing a LEMP stack takes one apt command; the part that trips people up is connecting Nginx to PHP-FPM correctly.

This guide walks through the whole path on Ubuntu and Debian: installing the packages, securing MariaDB and creating a database, writing the server block with the right PHP socket, testing, permissions, the firewall and HTTPS, plus the differences on AlmaLinux and the most common errors.

What is a LEMP stack, and how does it differ from LAMP?

In a LEMP stack, Nginx receives the requests and serves static files, PHP-FPM runs the PHP code as a separate service and MariaDB stores the data. A LAMP stack uses Apache in place of Nginx. Apache can run PHP inside itself and reads .htaccess files in every folder; Nginx does neither. It hands PHP requests to PHP-FPM over a socket and keeps all rules in its own configuration, and in return it handles many simultaneous connections with little memory. We compare the web servers in our How to install Nginx guide.

Step 1: Install Nginx, MariaDB and PHP-FPM

After connecting to your server over SSH:

sudo apt update
sudo apt install nginx mariadb-server php-fpm php-mysql \
  php-cli php-curl php-mbstring php-xml php-zip php-gd

php-fpm is the service that runs PHP; install it rather than the plain php package, which can pull in Apache as a dependency. php-mysql lets PHP talk to MariaDB, and the rest are extensions that WordPress, Laravel and most other applications expect. Nginx and MariaDB start on their own; check them with systemctl status nginx mariadb and note the installed PHP version with php -v.

Step 2: Secure MariaDB and create a database

Run the security script that comes with MariaDB:

sudo mariadb-secure-installation

On older versions the same script is called mysql_secure_installation. On Ubuntu and Debian, root already logs in through unix_socket, so press Enter at the current root password prompt, answer n to switching to unix_socket and to changing the root password, and Y to the rest: remove anonymous users, disallow remote root login, remove the test database and reload the privilege tables.

Then open the console with sudo mariadb and create a database with its own user for your site:

CREATE DATABASE app CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'app'@'localhost' IDENTIFIED BY 'a-strong-password';
GRANT ALL PRIVILEGES ON app.* TO 'app'@'localhost';
FLUSH PRIVILEGES;
EXIT;

Your application connects with host localhost, the database app, the user app and this password. Remote access, backups and tuning are covered in our How to install MariaDB guide.

Step 3: Find the PHP-FPM socket

Nginx reaches PHP-FPM through a Unix socket, and on Ubuntu and Debian the socket name contains the PHP version. Don't copy it from a guide; look it up:

ls /run/php/

You will see a file such as php8.3-fpm.sock (Ubuntu 24.04) or php8.2-fpm.sock (Debian 12). The service is named the same way, for example php8.3-fpm. In the commands and paths below, replace 8.3 with your version.

Step 4: Create the Nginx server block

Make sure your domain's A record points to the server (see What is DNS?), create the site folder with sudo mkdir -p /var/www/yourdomain.com and then create the file /etc/nginx/sites-available/yourdomain.com:

server {
    listen 80;
    listen [::]:80;
    server_name yourdomain.com www.yourdomain.com;

    root /var/www/yourdomain.com;
    index index.php index.html;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}
  • root and index: The folder with your site's files, and the file to open for a folder. index.php has to be listed, or Nginx won't find your start page.
  • try_files: Serves the file or folder if it exists, otherwise returns 404. Applications that route every address through index.php, such as WordPress and Laravel, use try_files $uri $uri/ /index.php?$args; instead.
  • location ~ \.php$: Passes every request ending in .php to PHP-FPM. The snippets/fastcgi-php.conf file ships with Nginx on Ubuntu and Debian and sets the required FastCGI parameters, including SCRIPT_FILENAME.
  • fastcgi_pass: The socket from step 3.
  • The last block denies access to hidden files such as .env and .git.

Enable the site, test the configuration and reload Nginx:

sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

Step 5: Test PHP with info.php

Create a temporary test file:

echo '<?php phpinfo();' | sudo tee /var/www/yourdomain.com/info.php

Open http://yourdomain.com/info.php. If you see the PHP information page, with FPM/FastCGI in the Server API row, Nginx and PHP-FPM are talking to each other; the mysqli and pdo_mysql sections show that the database extension is loaded. The page reveals versions, paths and settings to anyone, so delete it as soon as you are done with sudo rm /var/www/yourdomain.com/info.php.

Step 6: File ownership and permissions

On Ubuntu and Debian, both Nginx and PHP-FPM run as the www-data user. That user has to be able to read your files, and write only where the application stores uploads or cache:

sudo chown -R $USER:www-data /var/www/yourdomain.com
sudo find /var/www/yourdomain.com -type d -exec chmod 755 {} \;
sudo find /var/www/yourdomain.com -type f -exec chmod 644 {} \;

Hand only the folders PHP must write to over to www-data, for example with sudo chown -R www-data:www-data /var/www/yourdomain.com/uploads; your application's documentation names them. Never fix a permission problem with 777. The numbers are explained in our Linux file permissions guide.

Step 7: Firewall and HTTPS

Open ports 80 and 443 in the firewall:

sudo ufw allow 'Nginx Full'

If UFW isn't enabled yet, allow your SSH port before you enable it, or you will lock yourself out; the steps are in our How to use UFW guide. Then get a free certificate with Certbot, which also sets up the redirect to HTTPS and automatic renewal:

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

Wildcard certificates, renewal tests and Certbot errors are covered in our How to install Let's Encrypt SSL guide.

PHP-FPM settings worth knowing

  • php.ini: PHP-FPM has its own settings file, /etc/php/8.3/fpm/php.ini; the cli folder next to it only applies to the command line. Limits such as upload_max_filesize and memory_limit live here; for uploads you also need client_max_body_size in Nginx, as described in our WordPress upload size limit guide.
  • pm.max_children: In /etc/php/8.3/fpm/pool.d/www.conf, this value sets how many PHP requests can run at the same time. When every worker is busy, new requests have to wait and visitors can see errors. The right value depends on your RAM and on how much memory one PHP worker uses; we show how to calculate it in our 502 Bad Gateway guide.

Apply changes with sudo systemctl restart php8.3-fpm. If an application needs a different PHP version than your distribution ships, see How to change the PHP version. With the stack running, you can put an application on it: our How to install WordPress guide covers the manual installation, and How to deploy Laravel covers Composer, .env, queue workers and the scheduler.

Differences on AlmaLinux and Rocky Linux

You install the stack with sudo dnf install nginx mariadb-server php-fpm php-mysqlnd and start it with sudo systemctl enable --now nginx mariadb php-fpm. Site files go directly under /etc/nginx/conf.d/ with a .conf extension. The service is simply called php-fpm, its pool file is /etc/php-fpm.d/www.conf, it runs as the apache user by default and listens on /run/php-fpm/www.sock. The snippets/fastcgi-php.conf file doesn't exist there; the PHP block uses include fastcgi_params; together with fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; and fastcgi_pass unix:/run/php-fpm/www.sock; instead.

Folders PHP must write to belong to apache instead of www-data. SELinux is also active: if PHP can't write to a folder although the permissions are right, the folder is missing the httpd_sys_rw_content_t label. Set the label instead of turning SELinux off. In the firewall, open the http and https services with firewall-cmd.

Common LEMP errors

  • 502 Bad Gateway: Nginx can't reach PHP-FPM. The service is stopped or the socket in fastcgi_pass is wrong, typically after a PHP upgrade. Compare ls /run/php/ with your server block and check systemctl status php8.3-fpm; every other cause is in our 502 Bad Gateway guide.
  • "File not found." or a blank page: PHP-FPM gets a wrong script path or none at all. "File not found." (in the Nginx log: Primary script unknown) means that root points to the wrong folder or that www-data can't read it. A blank page usually means a bare include fastcgi_params; was used instead of snippets/fastcgi-php.conf, which leaves the SCRIPT_FILENAME parameter missing.
  • The PHP file is downloaded or shown as text: The location ~ \.php$ block is missing, or another site file answers the request. Check server_name and the link in sites-enabled.
  • 403 Forbidden: There is no index.php in the folder, index.php isn't listed in the index line, or www-data can't read the files.
  • The "Welcome to nginx!" page still opens: The request reaches the default site. Check server_name, or remove the default site with sudo rm /etc/nginx/sites-enabled/default and reload.

PHP errors are also written to the Nginx error log, so the first place to look is always sudo tail -f /var/log/nginx/error.log.

Nodesty servers for your LEMP stack

A LEMP stack needs a server with root access. Nodesty AMD Ryzen 9 9950X VPS plans answer PHP requests quickly thanks to high single-core speed, while AMD EPYC 7763 VPS plans offer plenty of RAM for running several sites and their databases on one server. Both come with NVMe storage, full root access, nShield DDoS protection and free daily backups kept for 7 days. If you would rather publish a PHP site without managing a server, our web hosting plans with LiteSpeed are the more practical choice.

Frequently Asked Questions

What is the difference between LEMP and LAMP?

The only difference is the web server. LAMP uses Apache, LEMP uses Nginx; the E comes from the way Nginx is pronounced, engine-x. Apache can run PHP inside itself and reads .htaccess files, while Nginx hands PHP requests to a separate PHP-FPM service and keeps all rules in its own configuration files.

Which PHP version does apt install?

The php-fpm package installs the PHP version that ships with your distribution release, for example PHP 8.3 on Ubuntu 24.04 and PHP 8.2 on Debian 12. Run php -v to see the version. The version number is part of the service name and the socket name, so check it before you write the Nginx configuration.

Do .htaccess files work on a LEMP stack?

No. Nginx doesn't read .htaccess files, so rewrite and redirect rules written for Apache have no effect. You write the same rules in the server block instead; for most PHP applications a single try_files line that sends unknown addresses to index.php is enough.

Why does my browser download the PHP file instead of running it?

Nginx isn't passing the request to PHP-FPM, so it serves the file like any static file. Usually the location block for PHP files is missing from the server block, or the request is being answered by another site file such as the default site. Add the block, test with sudo nginx -t and reload Nginx.

Why do I get 502 Bad Gateway after installing or upgrading PHP?

Nginx can't reach PHP-FPM. Either the PHP-FPM service isn't running, or the socket path in the fastcgi_pass line doesn't match the socket that exists on the server. After a PHP upgrade the socket name changes with the version; list the /run/php folder and update the path.

Can I set up a LEMP stack on Nodesty web hosting?

Our web hosting plans run on the LiteSpeed web server, and PHP and the database are ready to use from the control panel, so there is nothing to install. If you want to install and manage Nginx, MariaDB and PHP-FPM yourself, you need a VPS with root access.

Nodesty

About the author

Nodesty Team · Infrastructure & Support

The Nodesty team runs our servers, network and DDoS protection day to day and answers customer support requests around the clock. These guides come from that work.

Related articles

Launch your server now.

Build, scale, and conquer without limits on Nodesty's premium infrastructure.

                                                                                                                                                                                                                            
                                                                                                                                                                                                                            
                                                                                                                                                                                                                            
                                                                                                                             ············································                                                   
                                                ··································································································..........···························                                     
                                       ················..........................................................................................................................··············                             
                                  ·············.................::::::::::::::::::::::::::::::::::::::::::::::....................:::::::::::::::::::::::::::::::::::::::................···········                        
                             ············................:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::............·········                     
                         ············.................:::::::::::::::::::::::::::::::::::::::::::::::::::------------::::::::::::::::::::::::::::::----------------:::::::::::::::::::::..........········                  
                    ············......................::::::::::::::::::::::::::::::::::::------------------------------------------------------------------------------------:::::::::::::.........········                
                ··········.............................................::::::::::::::::::-------------==========================================-----------------------------------:::::::::::........·······               
             ········..................:.....................................::::::::::--------=======+++++++++++++++++++++++++++++++++++++=========================------------------::::::::::.......·······              
           ······.........::::::::::::::::::::................................:::::::-----=====++++xxxxxx**************************xxxxxxxxx++++++++++++++===================------------::::::::.......·······             
          ·····.......:::::::::::::::::::::::::::.............................:::::----===+++xxx****%%%%&&&&&&#############&&&&&&&%%%%%*******xxxxxxxx++++++++++++++==============----------:::::::......······             
         ····......::::::::-------------:::::::::::..........................::::---===+++xx***%%%&&&####@@@@@@@@@@@@@@@@@@@@@@@@####&&&&&%%%%*******xxxxxxxxx+++++++++++++===========--------::::::......·····             
        ····.....:::::::--------------------:::::::::.......................::::---===++xxx**%%&&&###@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@###&&&&%%%%%********xxxxxxxxxxx++++++++++++========------::::::.....······            
        ····.....:::::--------------------------::::::::....................::::---===++xx***%%&&&####@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@###&&&&&%%%%%**********xxxxxxxxxxxxx+++++++++=======------:::::.....·····            
        ····....::::::-------=============---------:::::::::................:::::---===+++xx***%%%&&&#####@@@@@@@@@@@@@@@@@@@@@@@@@#####&&&&&%%%%%%*************xxxxxxxxxxxxxx+++++++++======-----:::::....·····            
         ····....:::::-------================---------:::::::::...............:::::----===++++xxx***%%%%&&&&&&#################&&&&&&%%%%%%%*******************xxxxxxxxxxxxxxxxx++++++++======----:::::....·····            
         ·····....:::::--------=================---------::::::::::..............:::::::-----====+++++xxxxxx**************************xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx++++++++=====-----::::....·····            
          ·····.....:::::--------=================----------:::::::::::.................:::::::::-------=============++++++++++++++++++++++++++++++++++++xxxxxxxxxxxxxxxxxxxxxxx++++++++======-----::::....·····            
            ·····.....:::::::----------===========-------------::::::::::::.........................::::::::::::::::::------------------=============+++++++++++++++++++++++++++++++++=======-----::::.....·····            
              ······......:::::::---------------------------------:::::::::::::........................................:::::::::::::::-----------============+++++++++++++++++++++========------:::::.....·····             
                 ······........:::::::::---------------------------:::::::::::::::::...........................................:::::::::::::------------=============================--------::::::.....······              
                    ·········.........:::::::::::::::-------------::::::::::::::::::::::::.......................................::::::::::::::::--------------------------------------::::::::......·······                
                          ··········............::::::::::::::::::::::::::::::::::::::::::::::::::................................::::::::::::::::::::::::::-------------:::::::::::::::.........········                   
                                  ············..................:::::::::::::::::::::::::::::::::::::::::::.........................:::::::::::::::::::::::::::::::::::::................···········                        
                                             ················.............................................................................................................·················                                 
                                                           ······················................................................................···························                                                
                                                                               ·········································································