Installing Nginx, PHP-FPM and MariaDB (LEMP) on an Ubuntu server
With this guide you install the LEMP stack of Nginx, PHP-FPM and MariaDB on an Ubuntu 24.04 or 26.04 LTS server and get your first site ready to go live with secure defaults. The commands do not hard-code a PHP version; they detect the version installed on your server.
Prerequisites and package installation
- An up-to-date system and a user with sudo rights: the first 30 minutes checklist.
- An active firewall (make sure the SSH port stays open): the UFW and firewalld guide.
- Your domain name's A record pointing to your server's IP address (DNS records). Our servers use IPv4 only, so do not add an AAAA record.
Replace example.com in the commands with your own domain name. Install the packages with a single command:
sudo apt update
sudo apt install nginx mariadb-server php-fpm php-mysql php-cli php-curl php-gd php-mbstring php-xml php-zip php-intl php-bcmath unzipFind your PHP version
Unversioned package names such as php-fpm install the default PHP version of your Ubuntu release (8.3 on Ubuntu 24.04, a newer version on 26.04). Because the configuration paths and the service name include this version, detect it once and store it in a variable:
php -v
ls /run/php/
PHPV=$(php -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;')
echo "$PHPV"
systemctl status "php$PHPV-fpm" --no-pagerThe ls /run/php/ output shows a socket such as php8.3-fpm.sock. In the rest of this guide, file paths use X.Y for the version, and commands use the $PHPV variable. The variable only exists in the current session, so define it again in a new SSH session.
Secure MariaDB and create a database
sudo mariadb-secure-installationOn Ubuntu, the MariaDB root account is authenticated by the operating system user (unix_socket) rather than a password, so sudo mariadb connects without asking for one. In the wizard, press Enter when asked for the current root password, answer "n" to switching to unix_socket authentication and to changing the root password, and answer "Y" to removing anonymous users, disallowing remote root login, removing the test database and reloading the privilege tables. Then create a separate database and user for your application:
sudo mariadbCREATE 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;utf8mb4 is the character set that can store every Unicode character, emoji included. Defining the user for localhost only means you do not need to expose the database to the internet: on Ubuntu, MariaDB listens only on 127.0.0.1 by default. Confirm this with sudo ss -tlnp | grep 3306, and test logging in as the new user with mariadb -u app -p app.
Site directory and Nginx server block
Directory and permissions
sudo mkdir -p /var/www/example.com/public
sudo chown -R www-data:www-data /var/www/example.com
sudo find /var/www/example.com -type d -exec chmod 755 {} +
sudo find /var/www/example.com -type f -exec chmod 644 {} +Directories get 755 and files get 644; Nginx and PHP-FPM run as the www-data user. For a stricter setup, you can make your own deployment user the owner of the files and leave only the upload and cache folders writable for www-data; that way a compromised PHP script cannot modify the application code.
The server block
Create the file /etc/nginx/sites-available/example.com (for example with sudo nano /etc/nginx/sites-available/example.com):
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/public;
index index.php index.html;
client_max_body_size 64M;
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/phpX.Y-fpm.sock;
}
# Hidden files such as .git and .env; .well-known stays open for Let's Encrypt
location ~ /\.(?!well-known) {
deny all;
}
}The try_files line passes the request to index.php when the requested file or folder does not exist; the clean URLs of applications such as WordPress and Laravel depend on this. Ubuntu's ready-made snippets/fastcgi-php.conf snippet never passes nonexistent PHP files to PHP-FPM. The hidden files rule blocks downloads of the .git directory or the .env file. client_max_body_size sets the largest file you can upload.
Enable the site
Replace X.Y in the fastcgi_pass line with your version, enable the site, remove the default site and open the web ports:
sudo sed -i "s/phpX.Y-fpm/php$PHPV-fpm/" /etc/nginx/sites-available/example.com
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
sudo ufw allow 'Nginx Full'
sudo ufw statusDo not continue until nginx -t reports "syntax is ok" and "test is successful". With a broken configuration, reload is rejected and the old configuration keeps running, whereas restart can take the site down completely. The "Nginx Full" profile opens ports 80 and 443 together.
Test PHP and adjust php.ini settings
echo '<?php phpinfo();' | sudo tee /var/www/example.com/public/info.php
curl -s http://example.com/info.php | grep -o 'PHP Version [0-9.]*' | head -1
# If DNS has not propagated yet, test with the server IP and a Host header
curl -s -H 'Host: example.com' http://SERVER_IP/info.php | grep -o 'PHP Version [0-9.]*' | head -1
sudo rm /var/www/example.com/public/info.phpThis page shows everyone your PHP version, loaded modules, file paths and environment variables, which is exactly the information attackers look for. Delete the file as soon as you finish testing.
Upload limits and memory settings are read from FPM's own php.ini file: /etc/php/X.Y/fpm/php.ini. The command-line php, on the other hand, uses /etc/php/X.Y/cli/php.ini, so the value you see in php -i is not the value your site uses. Creating a separate file instead of editing the main one avoids configuration conflicts during package updates:
printf 'upload_max_filesize = 64M\npost_max_size = 64M\nmemory_limit = 256M\n' | sudo tee "/etc/php/$PHPV/fpm/conf.d/99-custom.ini"
sudo systemctl restart "php$PHPV-fpm"
sudo "php-fpm$PHPV" -i | grep -E 'upload_max_filesize|post_max_size|memory_limit'post_max_size should not be smaller than upload_max_filesize. Nginx's client_max_body_size must be at least as large too; otherwise large uploads stop at Nginx with a "413 Request Entity Too Large" error before they reach PHP.
Size the PHP-FPM pool for your RAM
The pool settings are in /etc/php/X.Y/fpm/pool.d/www.conf. There are two common modes:
- pm = dynamic: A set number of processes wait ready; this reduces latency for sites with steady traffic.
- pm = ondemand: Processes start as requests arrive and stop when idle; this saves memory on low-traffic sites or servers with little RAM.
pm = dynamic
pm.max_children = 20
pm.start_servers = 4
pm.min_spare_servers = 2
pm.max_spare_servers = 6
pm.max_requests = 500The most critical value is pm.max_children: the RAM you can give PHP ÷ the average memory per process. The measurement and calculation are explained in the swap and OOM guide. pm.max_requests recycles each process after a set number of requests to guard against memory leaks. After making changes, restart the service with sudo systemctl restart "php$PHPV-fpm".
Configuration files, logs and common errors
| Component | Configuration | Logs |
|---|---|---|
| Nginx | /etc/nginx/nginx.conf, /etc/nginx/sites-available/ | /var/log/nginx/error.log and the per-site logs |
| PHP-FPM | /etc/php/X.Y/fpm/php.ini, conf.d/, pool.d/www.conf | /var/log/phpX.Y-fpm.log; application errors go to the site's Nginx error log |
| MariaDB | /etc/mysql/mariadb.conf.d/50-server.cnf | journalctl -u mariadb |
| Services | systemctl status nginx mariadb phpX.Y-fpm | journalctl -u nginx, journalctl -u phpX.Y-fpm |
PHP application errors appear in the Nginx error log with the prefix "FastCGI sent in stderr". Common errors and where to look first:
- 502 Bad Gateway: PHP-FPM is not running, or the socket path in the
fastcgi_passline is wrong. Check withsystemctl status "php$PHPV-fpm"andls /run/php/; the Nginx error log shows aconnect() to unix:/run/php/... failedline. - The PHP file downloads or the code shows as plain text: The
location ~ \.php$block is missing, or the request lands in another server block; check the enabled sites withls -l /etc/nginx/sites-enabled/. - "File not found." or 404: The
rootpath is wrong or the file does not exist; the Nginx error log shows the full path it looked for. - 403 Forbidden: There is no index file in the directory, or Nginx cannot read the file; check the permissions.
- 413 Request Entity Too Large:
client_max_body_sizeis smaller than the uploaded file. - "Access denied for user 'app'@'localhost'": The database name, user name or password in the application is wrong; try it by hand with
mariadb -u app -p app.
Next steps
Now that the site works over HTTP, HTTPS is next: the free SSL with Let's Encrypt guide adds a certificate on top of this server block. After that, install Fail2ban against brute-force attempts, set up a backup strategy for the database and site files, and take a snapshot before major changes.
Frequently asked questions
Can I install a different PHP version from the one Ubuntu ships?
The Ubuntu repositories offer a single PHP version for each LTS release. You can use third-party repositories for a different version; in that case, remember that security updates come from that repository and that package names (such as phpX.Y-fpm) change. Update the socket path in the Nginx configuration to match the new version as well.
Nginx or Apache?
Nginx serves static files with little memory and hands PHP off to PHP-FPM. It does not support .htaccess files; rewrite rules go into the server block. If you have an application that ships its rules in .htaccess, you need to translate them into Nginx syntax.
Can I host more than one site on the same server?
Yes. Create a separate directory and a separate server block for each site. Giving each site its own PHP-FPM pool and its own system user makes it harder for a compromised site to reach the files of the others.
Related articles
Thanks for your feedback!