NewCode CLOUD — 20% off your first month on all cloud VPSClaim

How to Install a LEMP Stack (Nginx, MariaDB, PHP-FPM) on Ubuntu 24.04 and Debian 12

LEMP — Linux, Nginx (pronounced “engine-x”), MySQL/MariaDB and PHP — runs a large share of the web, including WordPress, Laravel, Magento and most PHP applications. Compared with the classic Apache-based LAMP stack, Nginx uses less memory per connection and handles static files and many concurrent visitors very efficiently, which makes it a good fit for VPS plans of any size.

This guide installs and configures a production-ready LEMP stack on Ubuntu 24.04 or Debian 12. Commands for Ubuntu 22.04 are the same apart from the PHP version.

Before you start

  • A fresh server with a sudo user and a firewall.
  • A domain name with an A record pointing to the server’s IP (needed for SSL later) — see DNS records explained.
  • About 1 GB of RAM is enough for a small site; add swap on the smallest plans.
sudo apt update && sudo apt upgrade -y

Step 1: Install Nginx

sudo apt install nginx -y
sudo systemctl enable --now nginx
sudo ufw allow 'Nginx Full'          # ports 80 and 443

Visit http://YOUR_SERVER_IP — you should see the “Welcome to nginx” page.

Step 2: Install MariaDB

MariaDB is a drop-in replacement for MySQL and the default in Debian and Ubuntu repositories.

sudo apt install mariadb-server -y
sudo systemctl enable --now mariadb
sudo mariadb-secure-installation

Answers for the security script:

  • Switch to unix_socket authentication: n (root already uses it on Debian/Ubuntu)
  • Change root password: n (socket auth means root logs in via sudo mariadb)
  • Remove anonymous users: Y
  • Disallow root login remotely: Y
  • Remove test database: Y
  • Reload privilege tables: Y

Create a database and user for your site:

sudo mariadb
CREATE DATABASE sitedb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'siteuser'@'localhost' IDENTIFIED BY 'use-a-long-random-password';
GRANT ALL PRIVILEGES ON sitedb.* TO 'siteuser'@'localhost';
FLUSH PRIVILEGES;
EXIT;

Use utf8mb4 so the database stores Chinese characters and emoji correctly. More on securing and tuning MariaDB in install and secure MariaDB.

Step 3: Install PHP-FPM

Nginx does not run PHP itself; it passes requests to PHP-FPM (FastCGI Process Manager).

sudo apt install php-fpm php-mysql php-curl php-gd php-mbstring php-xml php-zip php-intl php-bcmath php-imagick -y
php -v

Ubuntu 24.04 installs PHP 8.3; Debian 12 installs PHP 8.2. Note the version — it appears in file paths below. Check that FPM is running and find its socket:

systemctl status php8.3-fpm
ls /run/php/

Step 4: Create the site

sudo mkdir -p /var/www/example.com/public
sudo chown -R $USER:www-data /var/www/example.com
sudo chmod -R 750 /var/www/example.com
echo "<?php phpinfo();" > /var/www/example.com/public/info.php

Step 5: Nginx server block

Create /etc/nginx/sites-available/example.com:

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

    root /var/www/example.com/public;
    index index.php index.html;

    access_log /var/log/nginx/example.com.access.log;
    error_log  /var/log/nginx/example.com.error.log;

    client_max_body_size 64M;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

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

    # Block hidden files such as .git and .env
    location ~ /\.(?!well-known) {
        deny all;
    }

    location ~* \.(css|js|jpg|jpeg|png|gif|webp|svg|ico|woff2?)$ {
        expires 30d;
        access_log off;
    }
}

Enable it and remove the default site:

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo rm /etc/nginx/sites-enabled/default
sudo nginx -t && sudo systemctl reload nginx

Open http://example.com/info.php. If you see the PHP information page, the stack works. Delete it immediately — it reveals configuration details:

rm /var/www/example.com/public/info.php

Step 6: HTTPS with Let’s Encrypt

sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d example.com -d www.example.com

Certbot edits the server block, adds the certificate and sets up automatic renewal. Details and troubleshooting: Nginx and Let’s Encrypt on Ubuntu.

Step 7: Tune PHP

Create an override file rather than editing the main php.ini:

sudo nano /etc/php/8.3/fpm/conf.d/99-custom.ini
memory_limit = 256M
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 120
expose_php = Off

; OPcache: compiled PHP kept in memory — large speed-up
opcache.enable = 1
opcache.memory_consumption = 192
opcache.max_accelerated_files = 20000
opcache.validate_timestamps = 1
opcache.revalidate_freq = 60

Keep upload_max_filesize in line with Nginx’s client_max_body_size.

PHP-FPM workers

The number of PHP workers decides how many requests run at once — and how much memory PHP uses. Edit /etc/php/8.3/fpm/pool.d/www.conf:

pm = dynamic
pm.max_children = 10
pm.start_servers = 3
pm.min_spare_servers = 2
pm.max_spare_servers = 5
pm.max_requests = 500

A rough rule: max_children ≈ (RAM available for PHP) ÷ (average memory per PHP process). Check the per-process size with:

ps -ylC php-fpm8.3 --sort:rss | awk '{sum+=$8; n++} END {print sum/n/1024 " MB average"}'

With 2 GB of RAM, MariaDB and Nginx running, 8–12 workers at ~60 MB each is typical. Restart after changes:

sudo systemctl restart php8.3-fpm

Multiple PHP versions

Some applications need an older or newer PHP. The widely used ondrej/php repository provides many versions side by side on Ubuntu (and packages.sury.org on Debian):

sudo add-apt-repository ppa:ondrej/php -y       # Ubuntu
sudo apt update
sudo apt install php8.2-fpm php8.2-mysql php8.2-mbstring php8.2-xml -y

Each version has its own socket (/run/php/php8.2-fpm.sock). Point each site’s fastcgi_pass at the version it needs.

Security basics

  • Run each site’s files owned by your deploy user with group www-data, not owned by www-data — see permissions.
  • Block PHP execution in upload directories.
  • Keep MariaDB listening on localhost only (default).
  • Hide the Nginx version: add server_tokens off; in the http block of /etc/nginx/nginx.conf.
  • Add rate limiting for logins and Fail2ban.

Troubleshooting

Problem Likely cause Check
502 Bad Gateway PHP-FPM not running or wrong socket path systemctl status php8.3-fpm; ls /run/php/
PHP file downloads instead of running location ~ \.php$ block missing or not matching nginx -t; check server block
504 Gateway Timeout Script running too long max_execution_time, fastcgi_read_timeout 120s;
413 Request Entity Too Large Upload larger than Nginx allows client_max_body_size
“Error establishing a database connection” Wrong credentials or DB not running sudo mariadb -u siteuser -p sitedb
Out-of-memory, random 502s Too many PHP workers Lower pm.max_children, add swap

Logs to check, in order: the site’s error log, /var/log/nginx/error.log, and journalctl -u php8.3-fpm.

Next steps