Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 67 ยท Security, Errors and Deployment

Deploying Laravel to Production

Deploy a Laravel app safely - Laravel Cloud, Forge or a VPS, nginx and PHP-FPM, secrets, optimize commands, Supervisor workers, zero-downtime releases and backups.

Running php artisan serve on your laptop is not deployment. A production Laravel application needs a web server pointed at the right folder, PHP tuned for speed, secrets that never touch Git, a database that is backed up, workers that restart when they crash, and a deploy routine that can be repeated at 5 p.m. on a Friday without fear.

This lesson walks through the choices and the checklist. You can host Laravel in three broad ways: a managed platform that does most of it for you, a server managed by a tool such as Forge, or a plain Linux server you run yourself. The commands and configuration files below are read-only because they run on a real server, not on this site. The runnable examples are plain-PHP tools that capture the logic: a pre-deploy checklist validator and a zero-downtime release switch.

Choose how you host

Option You manage Good for
Laravel Cloud Almost nothing: it builds, deploys, scales and provides databases, caches and queues Teams that want to ship, not administer servers
Laravel Forge Your own servers at a provider (Hetzner, DigitalOcean, AWS...); Forge installs and configures nginx, PHP, MySQL, Redis, SSL, workers and deploys Control over cost and servers without hand-writing configs
A plain VPS Everything: the OS, packages, nginx, PHP-FPM, security updates, backups Learning, or very tight budgets and special needs
Serverless or containers Images, orchestration, storage Large, spiky, or already-containerized workloads

If you are unsure, start with a managed option. The knowledge below still applies, because every option has to answer the same questions: where does the code live, how is it configured, and how does it keep running?

flowchart LR
    G["Git push"] --> B["Build: composer install,<br/>npm run build"]
    B --> R["New release folder"]
    R --> M["php artisan migrate --force"]
    M --> O["php artisan optimize"]
    O --> S["Switch 'current' symlink"]
    S --> Q["Restart queue workers<br/>and reload PHP-FPM"]

A typical deploy: build first, switch traffic last, and restart long-running processes at the end.

The server stack

A conventional Laravel server runs nginx (the web server), PHP-FPM (runs your PHP), a database (MySQL, MariaDB or PostgreSQL), and often Redis for cache, sessions and queues. Nginx serves static files itself and hands every other request to PHP-FPM, which runs public/index.php.

The single most important detail: the web root must be the public folder, never the project root. Everything else (.env, app, vendor) must not be reachable from the web.

NGINX
server {
    listen 80;
    server_name example.com;
    root /var/www/example/current/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 ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

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

Use HTTPS everywhere (a free Let's Encrypt certificate, or Cloudflare in front), and redirect HTTP to HTTPS. In config/app.php or a service provider you can call URL::forceHttps() in production when you sit behind a proxy that terminates TLS, and configure trusted proxies so Laravel reads the right scheme and client IP.

Turn on OPcache in PHP (it caches compiled PHP so files are not re-parsed on every request) and give PHP-FPM a sensible number of workers for your memory. Both are explained further in Performance and optimization.

Environment and secrets

Production needs its own .env (or real environment variables set by the platform). Rules that prevent most disasters:

INI
APP_NAME="My App"
APP_ENV=production
APP_DEBUG=false
APP_URL=https://example.com
APP_KEY=base64:...generated once with php artisan key:generate...

LOG_CHANNEL=stack
LOG_LEVEL=warning

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_DATABASE=app
DB_USERNAME=app
DB_PASSWORD=a-long-random-password

CACHE_STORE=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
SESSION_SECURE_COOKIE=true
  • .env is never committed to Git. Keep an .env.example with fake values.
  • APP_DEBUG=false and APP_ENV=production.
  • APP_KEY is generated once and never changed casually: it encrypts cookies and sessions, and changing it logs everyone out and breaks anything encrypted with it.
  • Use a database user with only the privileges the app needs, not root.
  • Rotate any secret that has ever been pasted into a chat, a ticket or a repository.

Laravel can also encrypt the file for storage in Git with php artisan env:encrypt, and decrypt it on the server with env:decrypt and a key held outside the repository.

The deploy script

A repeatable script is better than a checklist in someone's head. This is the heart of almost every Laravel deploy, whether it runs in Forge, GitHub Actions or a shell:

Terminal
git pull origin main                              # or unpack the new release

composer install --no-dev --optimize-autoloader --no-interaction
npm ci && npm run build                           # build assets (often done in CI instead)

php artisan migrate --force                       # --force is required in production
php artisan optimize                              # caches config, routes, events and views
php artisan storage:link                          # once, or idempotently on every deploy

php artisan queue:restart                         # workers pick up the new code
sudo service php8.4-fpm reload                    # refresh OPcache

Some details worth knowing:

  • composer install --no-dev leaves out testing and development packages, and --optimize-autoloader makes class loading faster.
  • php artisan optimize runs the config, event, route and view caches together. Once config is cached, env() outside config files returns null, so only read env() in config/*.php and use config() everywhere else. See Configuration and environments.
  • php artisan migrate --force changes your live database. Write migrations that are safe while the old code is still running: add a nullable column first, deploy code that uses it, and remove old columns in a later release.
  • queue:restart tells workers to finish their current job and then exit, so the process manager starts them again with fresh code.

Keep workers alive with Supervisor

Queue workers are long-running PHP processes (Queues and jobs). They can crash, run out of memory, or need restarting after a deploy, so a process manager such as Supervisor (or systemd) must supervise them:

INI
; /etc/supervisor/conf.d/laravel-worker.conf
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/example/current/artisan queue:work redis --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/var/www/example/storage/logs/worker.log
stopwaitsecs=3600

--max-time=3600 makes each worker exit after an hour so memory leaks cannot grow forever, and Supervisor restarts it. Add the scheduler with one cron line, as explained in Task scheduling:

Terminal
* * * * * cd /var/www/example/current && php artisan schedule:run >> /dev/null 2>&1

Zero-downtime deploys

If you deploy by pulling into the live folder, requests during the deploy can see half-updated code or a vendor folder in the middle of an install. The standard fix is release folders and a symlink:

TEXT
/var/www/example/
  releases/
    20260101-1200/     <- old release (still serving)
    20260101-1300/     <- new release (being built)
  shared/
    .env
    storage/           <- logs, uploads, cache live here, not in a release
  current -> releases/20260101-1300     <- nginx root points at current/public

You build the new release completely, link the shared .env and storage folders into it, run migrations and optimize, and only then repoint current to the new folder. The switch is a single atomic operation, so a visitor either gets the old release or the new one, never a mixture. Rolling back means pointing the symlink at the previous release. Forge's zero-downtime deployments, Laravel Envoy, Deployer and Laravel Cloud all work this way or offer an equivalent.

The stand-in below models the release switch with an array in place of the filesystem: build a release, run the health check, switch only if it passes, and keep a short history for rollback.

PHP A zero-downtime release switch with rollback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Backups, monitoring and security updates

A deploy process is only half of operations. Plan these before you need them:

  • Database backups: automatic, off the server, with a retention policy. The spatie/laravel-backup package is a popular way to dump the database and files on a schedule and send them to S3 or another disk. Managed databases usually offer point-in-time recovery.
  • Test restores. A backup you have never restored is a hope, not a backup.
  • Uploaded files: store user files on an object storage disk such as S3 (File uploads and storage) so servers stay replaceable.
  • Monitoring: an uptime check, error tracking (Flare, Sentry or similar, fed by the exception handler from Logging and errors), disk space alerts, and queue length alerts.
  • Updates: apply OS security patches, keep PHP on a supported version, and run composer audit regularly to spot vulnerable dependencies.
  • Firewall: expose only ports 80, 443 and SSH; databases and Redis listen on localhost or a private network.

A pre-deploy checklist you can automate

Many mistakes are repeats: debug left on, a missing key, .env in Git. A tiny script that checks the production environment before every deploy catches them. The example below validates a config array against rules. In a real project the same idea can be an Artisan command or a CI step that reads your deployed environment.

PHP A production checklist validator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What must the web server's document root point to?

    Only public/ should be reachable from the web. Pointing at the project root can expose .env, source code and vendor files.
  2. 2. Why does php artisan migrate need the --force flag in production?

    In the production environment Laravel prompts before running migrations. A deploy script is not interactive, so you pass --force once you are sure.
  3. 3. What makes a symlink-based release deploy "zero downtime"?

    Visitors keep being served by the old release while the new one is built. Repointing the current symlink is atomic, and rollback is just pointing it back.
  4. 4. Why run queue workers under Supervisor or systemd?

    Workers are long-running processes. A process manager keeps the configured number of them alive and starts them again with new code after a restart.
  5. 5. After php artisan optimize caches the configuration, what happens to env() calls outside config files?

    With a cached config the .env file is not loaded, so env() outside config/*.php returns null. Read env() only in config files and use config() elsewhere.

Summary

  • Pick Laravel Cloud for least work, Forge for managed servers you own, or a VPS for full control.
  • Serve only public/ through nginx and PHP-FPM, use HTTPS, and enable OPcache.
  • Keep .env out of Git, set APP_DEBUG=false and APP_ENV=production, and protect APP_KEY.
  • A deploy script installs without dev packages, builds assets, runs migrate --force and optimize, then restarts workers and PHP-FPM.
  • Supervisor keeps queue workers alive, one cron line runs the scheduler, and release folders with a symlink give zero-downtime deploys and quick rollback.
  • Automate backups (and test restores), monitoring and pre-deploy checks.

Next: Architecture: Actions, Services and Clean Code