Skip to main content

Web frameworks · Advanced · 30 min

How to Deploy a Laravel App with Nginx and PHP-FPM

By Padding · Updated 15 Nov 2026
Ubuntu 26.04.1 LTS · Laravel 13 · PHP 8.5 (PHP-FPM) · Nginx 1.30

You will serve a Laravel 13 app on Ubuntu 26.04 with Nginx 1.30 passing PHP requests to a dedicated PHP-FPM 8.5 pool over a Unix socket, with APP_DEBUG off, a private .env file, code the app user cannot change, a production cache, and a repeatable deploy script.

On this page

Running php artisan serve is fine on your own computer and wrong on a server. For production, the usual stack has three parts. Nginx faces the internet, serves static files and handles slow clients. PHP-FPM, the FastCGI Process Manager, keeps a pool of PHP worker processes and runs your code. systemd starts both at boot and restarts them if they die. Nginx hands PHP requests to PHP-FPM over a Unix socket, a file that two programs on the same machine use to talk to each other.

This tutorial sets that stack up for a Laravel 13 app on Ubuntu 26.04. It follows the settings that matter in production: APP_DEBUG off, the secret key and settings in a file only the right users can read, a PHP-FPM pool that runs as its own unprivileged user, application code that the app cannot rewrite, and the caches that make Laravel fast. It ends with a deploy script you can run for every release.

Nginx is not installed here. Follow the Nginx install tutorial first, which gives you the stable Nginx 1.30 from nginx.org and a nginx user. For installing PHP and Composer, and for what a Laravel project contains, see the Laravel 13 install tutorial. The SQLite database keeps this tutorial short. For a bigger app, use PostgreSQL or MySQL, as in the PostgreSQL 18 tutorial.

Step 1 · Install PHP-FPM and create the app user

PHP-FPM is a separate package from the command-line PHP. Install it with the extensions Laravel needs. If you followed the Laravel install tutorial, most are already there, and apt skips them:

Bash
sudo apt update
sudo apt install -y php8.5-fpm php8.5-cli php8.5-mbstring php8.5-xml php8.5-curl php8.5-zip php8.5-sqlite3 php8.5-bcmath php8.5-intl unzip git curl

The package sets up a service named php8.5-fpm and a default pool called www that runs as www-data and listens on /run/php/php8.5-fpm.sock. You will not use it. A pool of your own, running as a dedicated user, keeps this app's processes and files apart from anything else on the server.

Create the user. It has no password, no login shell and no home folder, so a flaw in the app cannot become a login:

Bash
sudo useradd --system --user-group --no-create-home --home-dir /srv/notes --shell /usr/sbin/nologin laravel

Create the folders. The code lives in /srv/notes/app and is owned by root, so the app cannot change its own source. The SQLite database lives in /var/lib/notes, which only the app user can write:

Bash
sudo install -d -m 755 /srv/notes
sudo install -d -o laravel -g laravel -m 750 /var/lib/notes

Check it worked

Bash
id laravel
ls -ld /srv/notes /var/lib/notes
php-fpm8.5 --version | head -1

id laravel shows a user and a group named laravel. The two folders are listed with owners root and laravel. The last line starts with PHP 8.5. and ends with (fpm-fcgi).

Step 2 · Put the code on the server

In real life you clone your repository: sudo git clone <your repository URL> /srv/notes/app. Here, a fresh Laravel 13 project stands in for your code. The --no-scripts flag stops Composer from creating a world-readable .env file on its own, because you will create that file yourself with the right permissions:

Bash
cd /srv/notes
sudo composer create-project laravel/laravel:^13.0 app --no-interaction --no-scripts --no-dev

Install the dependencies the way production needs. --no-dev skips test and development packages, and --optimize-autoloader builds a class map so Composer does not search the disk for classes. Running these as root is deliberate, because the code should be owned by root. Composer will warn that running as root is not recommended: that warning is aimed at people who do it by accident, and here it is the point.

Bash
cd /srv/notes/app
sudo composer install --no-dev --optimize-autoloader --no-interaction --no-scripts

Because of --no-scripts, Composer did not run Laravel's package discovery. Laravel writes its compiled caches into storage and bootstrap/cache, so give those two folders to the app user now, and run the discovery as that user. From here on, run every Artisan command as laravel, never as root, so the files it creates have the right owner:

Bash
cd /srv/notes/app
sudo chown -R laravel:laravel storage bootstrap/cache
sudo chmod -R u+rwX,g-w,o-rwx storage bootstrap/cache
sudo -u laravel php artisan package:discover --ansi

Add a route that fails on purpose. You will use it to prove that production hides error details. A controller is used instead of a closure so the route cache works:

Bash
sudo tee /srv/notes/app/app/Http/Controllers/BoomController.php > /dev/null <<'PHP'
<?php

namespace App\Http\Controllers;

class BoomController extends Controller
{
    public function __invoke()
    {
        throw new \RuntimeException('secret detail: database password is hunter2');
    }
}
PHP
sudo tee -a /srv/notes/app/routes/web.php > /dev/null <<'PHP'

Route::get('/boom', \App\Http\Controllers\BoomController::class);
PHP

Remove that route when you are done with this tutorial. It exists only for the check below.

Step 3 · Write the production environment file

Laravel reads its settings from .env. Create the file empty first, with its permissions already set, so the secrets are never in a readable file even for a moment. Root owns it and the laravel group can read it, and nobody else:

Bash
sudo install -m 640 -o root -g laravel /dev/null /srv/notes/app/.env

Write the settings. APP_ENV=production and APP_DEBUG=false matter most: with debug on, an error page prints code, file paths and configuration to every visitor. Change APP_URL to your domain:

Bash
sudo tee /srv/notes/app/.env > /dev/null <<'ENV'
APP_NAME=Notes
APP_ENV=production
APP_DEBUG=false
APP_URL=http://example.com

LOG_CHANNEL=stack
LOG_STACK=single
LOG_LEVEL=warning

DB_CONNECTION=sqlite
DB_DATABASE=/var/lib/notes/database.sqlite

SESSION_DRIVER=database
CACHE_STORE=file
QUEUE_CONNECTION=sync
ENV

The file is written in place with tee, which keeps the permissions of the file you created. Now generate the application key. key:generate --show only prints a key and does not change .env itself, so the key goes into the file through a pipe, and sed adds the APP_KEY= name in front. No temporary file is created, and the key never appears in your shell history or the process list:

Bash
cd /srv/notes/app
sudo -u laravel php artisan key:generate --show | sed 's/^/APP_KEY=/' | sudo tee -a .env > /dev/null

APP_KEY encrypts cookies and sessions. If you change it later, everyone is signed out, and anything encrypted with the old key can no longer be read.

Check it worked

Bash
cd /srv/notes/app
sudo ls -l .env
sudo grep -c '^APP_KEY=base64:' .env
sudo grep -E '^(APP_ENV|APP_DEBUG)=' .env

The listing starts with -rw-r----- and shows root laravel. The grep -c prints 1, which proves the key exists without printing it. The last command prints APP_ENV=production and APP_DEBUG=false.

Step 4 · Set permissions and prepare the database

Laravel needs to write in only three places: the storage folder for logs, cache and sessions, the bootstrap/cache folder for its compiled caches, and the database. The first two you handed to the app user in the previous step, and everything else stays read-only for it. Create the database file as the app user:

Bash
cd /srv/notes/app
sudo -u laravel touch /var/lib/notes/database.sqlite

Run the migrations as the app user. --force is required in production, because Laravel otherwise asks for confirmation before it changes a database in the production environment:

Bash
cd /srv/notes/app
sudo -u laravel php artisan migrate --force

Build the production caches. They merge your configuration into one file, your routes into one file, and compile the Blade views, so each request skips that work. The commands also run as the app user, so the cache files belong to it. Remember to run them again after you change .env, because a cached configuration no longer reads the file:

Bash
cd /srv/notes/app
sudo -u laravel php artisan optimize

Check it worked

Bash
cd /srv/notes/app
sudo ls -l bootstrap/cache
if sudo -u laravel touch /srv/notes/app/app/probe 2> /dev/null; then echo "app can write to its code: fix the permissions"; else echo "code is read-only for the app"; fi

bootstrap/cache lists config.php, routes-v7.php and others, owned by laravel. The last line is code is read-only for the app. php artisan optimize runs the config, event, route and view caches together.

Troubleshooting

If migrate says it cannot open the database, check that /var/lib/notes is owned by laravel and that the path in DB_DATABASE matches. If a command complains that it cannot write to storage, you probably ran an Artisan command as root, which created root-owned files there. Fix it with sudo chown -R laravel:laravel storage bootstrap/cache, then always run Artisan as the app user from now on.

Step 5 · Configure a PHP-FPM pool

Write the pool for this app. It runs as laravel, listens on a Unix socket, and lets the nginx group connect to it. The socket has mode 0660, so no other user on the server can send requests to your PHP:

Bash
sudo tee /etc/php/8.5/fpm/pool.d/notes.conf > /dev/null <<'INI'
[notes]
user = laravel
group = laravel

listen = /run/php/notes.sock
listen.owner = laravel
listen.group = nginx
listen.mode = 0660

pm = dynamic
pm.max_children = 8
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
pm.max_requests = 500
INI
sudo mv /etc/php/8.5/fpm/pool.d/www.conf /etc/php/8.5/fpm/pool.d/www.conf.disabled

The pm lines control how many PHP workers exist. dynamic starts a few and adds more under load, up to pm.max_children. That limit is the one to size carefully: each worker for a Laravel app often uses somewhere between 30 and 80 MB, so multiply your measured worker size by max_children and keep the total well under the server's free memory, or the server will start swapping or kill processes. pm.max_requests restarts a worker after 500 requests, which contains slow memory leaks. The second command disables the default www pool, since PHP-FPM loads only files ending in .conf.

Test the configuration before you restart anything:

Bash
sudo php-fpm8.5 --test

Now restart the service so it loads the new pool, and set it to start at boot:

Bash
sudo systemctl restart php8.5-fpm
sudo systemctl enable php8.5-fpm

Check it worked

php-fpm8.5 --test ends with configuration file /etc/php/8.5/fpm/php-fpm.conf test is successful. Check the service and the socket:

Bash
systemctl status php8.5-fpm
Bash
ls -l /run/php/notes.sock

systemctl status shows active (running). The socket listing starts with srw-rw---- and shows the owner laravel and the group nginx.

Step 6 · Configure Nginx

Laravel's own deployment guide gives the server block below. The document root is public, the only folder visitors should ever reach, so .env, vendor and the rest are outside it. Requests that match no file go to index.php, which is how Laravel's router receives every URL. Replace example.com with your domain.

The Nginx package from nginx.org ships a default.conf that already answers on port 80 as the default server. Move it aside first, or Nginx will use it and ignore yours for requests that do not match your server name. Anything that depended on the default page stops working:

Bash
sudo mv /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf.disabled
Bash
sudo tee /etc/nginx/conf.d/notes.conf > /dev/null <<'NGINX'
server {
    listen 80;
    listen [::]:80;
    server_name example.com;
    root /srv/notes/app/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;
    charset utf-8;

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

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/run/php/notes.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_hide_header X-Powered-By;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}
NGINX
sudo nginx -t

Three details matter. fastcgi_pass names the socket you configured in the pool, and the path must match exactly. $realpath_root in SCRIPT_FILENAME resolves symbolic links, which keeps PHP's opcache correct when you switch releases by changing a link. The last location blocks every hidden file, such as .env and .git, except .well-known, which Let's Encrypt needs. The fastcgi_hide_header line removes the X-Powered-By header, so visitors do not learn your PHP version.

Check it worked

nginx -t prints syntax is ok and test is successful. Apply the configuration and set Nginx to start at boot:

Bash
sudo systemctl reload nginx
sudo systemctl enable nginx

If the check fails with unknown directive or a missing include, the package's own fastcgi_params file should be at /etc/nginx/fastcgi_params. If you installed Nginx from the Ubuntu archive, the folder layout is different, with sites-available and sites-enabled, and the file is snippets/fastcgi-php.conf instead.

Step 7 · Test the deployment

If your domain does not point at the server yet, send the Host header yourself, as in the commands below. Request the home page, a page that does not exist, a hidden file, and the route that fails:

Bash
curl -s -o /dev/null -w 'home: %{http_code}\n' -H 'Host: example.com' http://127.0.0.1/
curl -s -H 'Host: example.com' http://127.0.0.1/ | grep -o '<title>[^<]*</title>'
curl -s -o /dev/null -w 'missing page: %{http_code}\n' -H 'Host: example.com' http://127.0.0.1/no-such-page
curl -s -o /dev/null -w '.env: %{http_code}\n' -H 'Host: example.com' http://127.0.0.1/.env
curl -s -o /tmp/boom.html -w 'boom: %{http_code}\n' -H 'Host: example.com' http://127.0.0.1/boom
curl -sI -H 'Host: example.com' http://127.0.0.1/ | grep -ci '^x-powered-by' || true

Check it worked

The output is home: 200, <title>Notes</title> (the APP_NAME from your .env), missing page: 404, .env: 403, boom: 500 and a final 0, the number of X-Powered-By headers. The 403 for .env comes from the rule that blocks hidden files. The file is not under public either, so Nginx could never serve it. Confirm that the failing route did not leak anything:

Bash
if grep -qiE 'hunter2|RuntimeException|Whoops|/srv/notes' /tmp/boom.html; then echo "LEAK: error details are visible"; else echo "no error details in the response"; fi
rm /tmp/boom.html

The output is no error details in the response. The visitor sees a plain "Server Error" page, and the real message is in /srv/notes/app/storage/logs/laravel.log, readable only by you and the app. With APP_DEBUG=true, the same request would have shown the exception, the file paths and the contents of your configuration.

Remove the test route now:

Bash
sudo rm /srv/notes/app/app/Http/Controllers/BoomController.php
cd /srv/notes/app
sudo sed -i '\|/boom|d' routes/web.php
php -l routes/web.php
sudo -u laravel php artisan optimize
sudo tail -n 3 routes/web.php

php -l prints No syntax errors detected, and the last lines of routes/web.php no longer mention /boom. Running optimize again rebuilds the route cache without it.

Troubleshooting

A 502 Bad Gateway means Nginx could not reach PHP-FPM. Check that the fastcgi_pass path matches the pool's listen line, that the service is running, and look at the end of /var/log/nginx/error.log: a Permission denied for the socket means the listen.group is not nginx. A download of the PHP source instead of a page means the location ~ \.php$ block is not being used, so check for typos. A 403 on ordinary pages means the nginx user cannot read /srv/notes/app/public, so check the folder permissions. A plain 500 from every page usually means storage or bootstrap/cache is not writable by laravel, or the .env file cannot be read by the group, and storage/logs/laravel.log has the reason.

Step 8 · Deploy new releases with a script

Every release repeats the same sequence, so write it down once. The script puts the site in maintenance mode, updates the code, installs dependencies, runs migrations, rebuilds the caches, reloads PHP-FPM, and brings the site back. The trap brings the site back even if a step fails, so a failed deploy does not leave visitors on the maintenance page forever. Read it before you run it, and adjust the git line to your branch:

Bash
sudo tee /usr/local/bin/deploy-notes > /dev/null <<'SH'
#!/bin/bash
set -euo pipefail
cd /srv/notes/app
artisan() { sudo -u laravel php artisan "$@"; }

artisan down --retry=60
trap 'artisan up' EXIT

git pull --ff-only
composer install --no-dev --optimize-autoloader --no-interaction
chown -R laravel:laravel storage bootstrap/cache
artisan migrate --force
artisan optimize
systemctl reload php8.5-fpm
SH
sudo chmod 755 /usr/local/bin/deploy-notes
bash -n /usr/local/bin/deploy-notes && echo "syntax ok"

Run it with sudo deploy-notes after you push a change. Reloading PHP-FPM clears the opcache, PHP's cache of compiled code, so the new code runs at once. The script uses git pull, which needs /srv/notes/app to be a Git checkout owned by a user that can pull. If your deploys come from CI, replace that line with whatever puts the new code in place. Test a deploy on a copy of the server before you trust it on the real one, and take a database backup before migrations that change tables.

Check it worked

The output is syntax ok. The check proves only that the script is valid shell, and the script's behaviour on your server is yours to test.

Step 9 · Run a queue worker and the scheduler, if you need them

If your app uses queued jobs (QUEUE_CONNECTION set to database, redis or similar), a worker process must run all the time, and systemd is the right supervisor. Create a unit for it. This is the same pattern as in the systemd service tutorial:

Bash
sudo tee /etc/systemd/system/notes-queue.service > /dev/null <<'UNIT'
[Unit]
Description=Notes queue worker
After=network.target

[Service]
User=laravel
Group=laravel
WorkingDirectory=/srv/notes/app
ExecStart=/usr/bin/php artisan queue:work --sleep=3 --tries=3 --max-time=3600
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
UNIT

--max-time=3600 makes the worker exit after an hour and systemd restart it, which picks up new code and frees memory. Workers keep the application in memory, so they do not notice a deploy by themselves: add artisan queue:restart to the deploy script if you use them. Start the worker and turn it on at boot:

Bash
sudo systemctl daemon-reload
sudo systemctl enable --now notes-queue
systemctl status notes-queue

For scheduled tasks (routes/console.php or the Laravel scheduler), one cron entry runs the scheduler every minute as the app user:

Bash
echo '* * * * * laravel cd /srv/notes/app && php artisan schedule:run >> /dev/null 2>&1' | sudo tee /etc/cron.d/notes-schedule

The cron.d file format has a user column, which is why laravel comes before the command. Skip both of these if your app has no queues or scheduled tasks.

Step 10 · Turn on HTTPS and clean up

The site answers on plain HTTP. Before real users arrive, add a certificate with free HTTPS from Let's Encrypt, and change APP_URL to the https:// address. After editing .env, run sudo -u laravel php artisan optimize again, because the cached configuration does not re-read the file. To harden the response headers further, see add security headers in Nginx.

To undo this tutorial, remove what it created. Stop the services first, and remove the files only after you are sure you do not need the database, because deleting it cannot be undone:

Bash
sudo systemctl disable --now notes-queue php8.5-fpm
sudo rm -f /etc/systemd/system/notes-queue.service /etc/cron.d/notes-schedule
sudo systemctl daemon-reload
Bash
sudo rm -f /etc/nginx/conf.d/notes.conf /etc/php/8.5/fpm/pool.d/notes.conf /usr/local/bin/deploy-notes /etc/systemd/system/notes-queue.service
sudo mv /etc/nginx/conf.d/default.conf.disabled /etc/nginx/conf.d/default.conf
sudo mv /etc/php/8.5/fpm/pool.d/www.conf.disabled /etc/php/8.5/fpm/pool.d/www.conf
sudo rm -rf /srv/notes /var/lib/notes
sudo userdel laravel

Then reload Nginx, restart PHP-FPM, and delete /etc/nginx/conf.d/default.conf again if you do not want the default page. sudo userdel laravel removes the user and, with it, its group.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.