Laravel in production

This cheat sheet brings together what you need to deploy a Laravel application to a production server and run it reliably: the deployment steps, the .env file, caching and permissions, Nginx and Apache, HTTPS behind a proxy, queues with Supervisor, the scheduler in cron, maintenance mode, and common problems. You can search for a command, filter by topic, and copy it with one click.

Deployment steps

  • composer install --no-dev --optimize-autoloader

    Installs the dependencies exactly as locked in the composer.lock file, without the development packages, and builds a faster autoload map. This is how you install dependencies on a production server.

  • npm ci && npm run build

    Installs the JavaScript packages from package-lock.json and uses Vite to build the CSS and JavaScript files into the public/build directory. Without this build, the site shows the Vite manifest not found error.

  • php artisan migrate --force

    Runs the migrations that haven't run yet. In the production environment, the command asks for confirmation, and the --force option skips it, so you can run it in a deployment script. Back up the database before migrations that drop or change columns.

  • php artisan migrate --isolated

    When several servers run the deployment at the same time, only one of them runs the migrations. The others skip them and finish successfully. This requires a cache shared by all the servers, for example Redis or a database.

  • php artisan optimize

    Caches the configuration, events, routes, and views (templates) in a single command. Run it on every deployment, after you update the code and the .env file.

  • php artisan storage:link

    Creates the public/storage symbolic link, which points to storage/app/public, so files your users upload are reachable from the browser. Run it on the first installation, and with release directories, on every new release as well.

  • php artisan reload

    Gracefully stops the long-running services so they start again with the new code: the queue workers (queue:restart), the current scheduler run (schedule:interrupt), and Laravel Octane when it's in use. It requires a process manager, such as Supervisor, to start them again.

  • curl -sI https://example.com/up

    Checks the built-in /up health route, a path for checking that the application is healthy: it returns 200 when the application boots without errors, and 500 when something is wrong. Suited to a check at the end of a deployment and to monitoring services.

The .env file for production

  • APP_ENV=production

    Sets the application environment to production. In this environment, dangerous commands, such as migrate, ask for confirmation before they run.

  • APP_DEBUG=false

    On a production server, the value must be false. With true, the error page exposes sensitive configuration details to visitors, such as paths, queries, and values from the .env file.

  • APP_URL=https://example.com

    The site's full URL, including https. Laravel uses it to generate links from Artisan commands and from queued jobs, where there's no HTTP request to take the URL from.

  • php artisan key:generate

    Generates an encryption key and writes it to APP_KEY in the .env file. Run it once on a new installation. Caution: in a live application, replacing the key logs out every signed-in user, and data encrypted with the previous key can no longer be decrypted. When you move an application to a new server, copy the existing key.

  • APP_PREVIOUS_KEYS="base64:..."

    When you replace APP_KEY, list the previous key here, or several keys separated by commas. Laravel encrypts only with the current key and also decrypts with the previous keys, so users stay signed in.

  • php artisan about --only=environment

    Shows the environment details: the environment name, debug mode, the site URL, and whether the configuration, routes, and views are cached. A quick check after a deployment.

Caching and performance

  • php artisan config:cache

    Combines all the configuration files into a single cache file. After it runs, the .env file isn't loaded, and the env() function returns null for every variable from .env. That's why you call env() only inside the files in the config directory, and use config() everywhere else in the code.

  • php artisan route:cache

    Saves all the routes in a single cache file. The improvement is most noticeable in applications with hundreds of routes.

  • php artisan view:cache

    Precompiles all the Blade templates, so they aren't compiled on the first request to each page.

  • php artisan event:cache

    Caches the mapping of automatically discovered events to their listeners.

  • php artisan optimize:clear

    Deletes all the cache files that optimize created, as well as all the keys in the application's default cache. Useful when you troubleshoot a problem. Afterward, run php artisan optimize again.

  • php artisan config:clear

    Deletes only the configuration cache, so .env is loaded again on every request. Useful to check whether a problem comes from a stale configuration cache.

Permissions and directories

  • sudo chown -R deploy:www-data storage bootstrap/cache

    Laravel writes to the storage and bootstrap/cache directories, so the user that runs PHP-FPM needs write access to them. In the example, the owner is the deployment user deploy, and the group is www-data, as on Debian and Ubuntu. On RHEL-based distributions, the group is usually nginx or apache.

  • sudo chmod -R ug+rwX storage bootstrap/cache

    Gives the owner and the group read and write permissions, and execute permission (entering) on directories only. Don't set 777 permissions, because then any user on the server can change the files.

  • ls -la public/storage

    Checks that the public/storage link exists and points to storage/app/public. When uploaded files return 404, the link is usually missing, so run php artisan storage:link.

Nginx

  • server { listen 80; listen [::]:80; server_name example.com; root /var/www/example/public; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; 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.ph

    A server block for a Laravel site, based on the example in the documentation. root points to the public directory only: never serve the project directory itself, because then files such as .env are exposed. try_files serves an existing file, and all other requests go to index.php.

  • ls /run/php-fpm/ /run/php/ 2>/dev/null

    Lists the PHP-FPM socket files, so you can write the correct path in fastcgi_pass. The path depends on the distribution and the PHP version: on RHEL-based distributions it's usually /run/php-fpm/www.sock, and on Debian and Ubuntu it's a file in the /run/php/ directory with the version in its name. The path is set by the listen setting of the pool.

  • fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;

    $realpath_root passes PHP the real path, after symbolic links are resolved. When the site is deployed in release directories with a current link, PHP then loads the files of the new release right after the link is switched.

  • sudo nginx -t && sudo systemctl reload nginx

    Checks the configuration syntax, and reloads the configuration only when the check passes, without dropping open connections.

Apache

  • <VirtualHost *:80> ServerName example.com DocumentRoot /var/www/example/public <Directory /var/www/example/public> AllowOverride All Require all granted </Directory> </VirtualHost>

    A VirtualHost for a Laravel site: DocumentRoot points to the public directory. The .htaccess file that ships in the public directory routes requests to index.php, and AllowOverride All lets Apache read it.

  • sudo a2enmod rewrite && sudo systemctl restart apache2

    On Debian and Ubuntu: enables the mod_rewrite module, which the Laravel .htaccess file needs. Without it, every URL except the home page returns 404.

  • sudo apachectl configtest

    Checks the Apache configuration syntax before a reload. The output Syntax OK means the configuration can be loaded.

HTTPS behind a proxy and Cloudflare

  • ->withMiddleware(function (Middleware $middleware): void { $middleware->trustProxies(at: [ '192.168.1.1', '10.0.0.0/8', ]); })

    In the bootstrap/app.php file: when a load balancer, Cloudflare, or a reverse proxy handles HTTPS and passes the request to the server over HTTP, Laravel doesn't know the visitor used HTTPS and generates http links. Registering the proxy addresses as trusted makes Laravel read the X-Forwarded-Proto and X-Forwarded-For headers.

  • $middleware->trustProxies(at: '*');

    Trusts any proxy. This setting suits cases where there's no fixed list of proxy addresses, provided the server receives traffic only through the proxy. Otherwise, a visitor can forge the headers and their IP address.

  • SESSION_SECURE_COOKIE=true

    The session cookie is sent only over HTTPS connections. On a site that runs entirely on HTTPS, turning this setting on is recommended.

Queues with Supervisor

  • php artisan queue:work --tries=3 --max-time=3600

    Processes jobs from the queue continuously. --tries=3 attempts each job up to three times before it's recorded as failed, and the --max-time=3600 option stops the worker after an hour, so Supervisor starts it again and frees memory that has built up.

  • php artisan queue:work --max-jobs=1000

    Stops the worker after 1,000 jobs, also to free memory. Supervisor starts it again.

  • php artisan queue:work --timeout=60

    Limits each job to 60 seconds. The value should be a few seconds shorter than retry_after in the config/queue.php file, which defaults to 90, otherwise a long job might run twice.

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

    The Supervisor program file, which on Debian and Ubuntu goes in the /etc/supervisor/conf.d/ directory. numprocs sets how many queue:work processes run in parallel, user runs them as a regular user rather than root, and stopwaitsecs should be longer than your longest job, otherwise Supervisor stops a job in the middle.

  • sudo dnf install supervisor && sudo systemctl enable --now supervisord

    On RHEL-based distributions, the package comes from the EPEL repository, which you need to enable first (on AlmaLinux and Rocky Linux with sudo dnf install epel-release), and the program files go in the /etc/supervisord.d/ directory with the .ini extension. On Debian and Ubuntu, install it with sudo apt-get install supervisor.

  • sudo supervisorctl reread && sudo supervisorctl update && sudo supervisorctl start "laravel-worker:*"

    Reads the new program files, applies the changes, and starts all the queue workers.

  • sudo supervisorctl status

    Shows the state of every process. RUNNING means the process is up, and FATAL or BACKOFF means it failed to start. You'll find the reason in the log file set in stdout_logfile.

  • php artisan queue:restart

    Queue workers load the code once and don't see changes. The command stops each worker after its current job, without losing jobs, and Supervisor starts it again with the new code. Run it on every deployment.

Failed jobs

  • php artisan queue:failed

    Lists the failed jobs, with the ID, connection, queue, and time of failure.

  • php artisan queue:retry all

    Pushes all the failed jobs back onto the queue. Fix the cause of the failure first.

  • php artisan queue:retry ce7bb17c-cdd8-41f0-a8ec-7b4fef4e5ece

    Pushes a single job back onto the queue, by its ID from the queue:failed output.

  • php artisan queue:prune-failed --hours=48

    Deletes jobs that failed more than 48 hours ago from the failed_jobs table, so the table doesn't grow without limit.

Task scheduler

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

    The only cron entry you need: it runs schedule:run every minute, which checks which scheduled tasks are due now. You define the tasks themselves in code, in the routes/console.php file.

  • sudo crontab -u deploy -e

    Edits the crontab of the user that runs the application, deploy in the example, rather than root's, so files the scheduler creates have the right owner.

  • php artisan schedule:list

    Lists all the scheduled tasks and the next run time of each one. A quick check that the scheduler sees the tasks.

  • php artisan schedule:work

    Runs the scheduler in the foreground and invokes it every minute, until you stop it with Ctrl+C. Intended for a development environment, instead of a cron entry.

  • php artisan schedule:interrupt

    When tasks run every few seconds, schedule:run keeps running with the old code until the end of the minute. The command stops it at the end of a deployment. php artisan reload includes it.

Maintenance mode

  • php artisan down --render="errors::503" --retry=60

    Puts the site into maintenance mode. --render prerenders the maintenance page, so it's shown even while composer updates the dependencies. The --retry=60 option sends the Retry-After header. Every request gets a 503 status code.

  • php artisan down --with-secret

    Maintenance mode with a bypass token: the command generates a random bypass token and displays it. Visiting https://example.com/<token> stores a cookie in your browser, so you can test the site while visitors see the maintenance page.

  • php artisan up

    Brings the site back online. During maintenance mode, queued jobs aren't processed and the scheduler doesn't run tasks. Everything resumes after up.

  • APP_MAINTENANCE_DRIVER=cache APP_MAINTENANCE_STORE=database

    By default, maintenance mode is stored in a file, so you run down on every server. With this setting, the state is stored in a shared cache, and a down command on one server applies to all of them.

Logs

  • LOG_CHANNEL=daily LOG_DAILY_DAYS=14

    A new log file every day, named laravel-YYYY-MM-DD.log, and files older than 14 days are deleted automatically. The default is a single file, storage/logs/laravel.log, which grows without limit.

  • LOG_LEVEL=warning

    The minimum severity level that gets logged. The levels, from most to least severe: emergency, alert, critical, error, warning, notice, info, and debug. The default, debug, logs everything.

  • tail -n 50 storage/logs/laravel.log

    Shows the last 50 lines of the log. With LOG_CHANNEL=daily, the file name includes the date, for example storage/logs/laravel-$(date +%F).log.

Common problems

  • tail -n 100 storage/logs/laravel.log

    With APP_DEBUG=false, the site shows only Server Error 500, with no details. The full cause, including the file and line, is written to the Laravel log. When the log is empty, check the error logs of the web server and PHP-FPM.

  • php artisan key:generate

    The No application encryption key has been specified error means the APP_KEY variable is empty. On a new installation, generate a key. For an existing application that moved to a new server, copy the key from the previous server, otherwise users are logged out and encrypted data can't be decrypted. After the change, run php artisan config:cache.

  • sudo chown -R deploy:www-data storage bootstrap/cache && sudo chmod -R ug+rwX storage bootstrap/cache

    The error The stream or file ".../storage/logs/laravel.log" could not be opened in append mode: Failed to open stream: Permission denied means PHP can't write to the log. Usually, the log file was created by root, for example by an Artisan command run with sudo. The command restores the ownership and permissions.

  • npm ci && npm run build && rm -f public/hot

    The error Vite manifest not found at: .../public/build/manifest.json means the CSS and JavaScript files weren't built on the server. After the build, delete the public/hot file if it was left over from running the development server: while it exists, pages load the files from the development server instead of from public/build.

  • php artisan config:show session

    The 419 Page Expired error when you submit a form means the CSRF token or the session isn't valid. Check that SESSION_DOMAIN matches the site's domain or is empty, that SESSION_SECURE_COOKIE=true is set only when the site runs on HTTPS, that the sessions directory or the sessions table is writable, and that the form includes @csrf.

  • grep -rn "env(" app routes resources/views

    A value that comes back as null after config:cache: the code calls env() outside the config directory. The command finds such calls. Move the value to a configuration file, read it with config(), and run php artisan config:cache again.

  • php artisan config:show queue

    Jobs that aren't processed: check that the connection (QUEUE_CONNECTION) is the one the queue workers listen on, that the workers show RUNNING in sudo supervisorctl status, and that the site isn't in maintenance mode. After a change in .env, run php artisan config:cache and php artisan queue:restart.

  • sudo systemctl status php-fpm

    When Nginx returns 502 Bad Gateway, PHP-FPM isn't running or the socket in fastcgi_pass is wrong. The command shows the status of the service. On Debian and Ubuntu, the service name also includes the PHP version.

  • composer dump-autoload --optimize

    A Class not found error after a deployment, when the class exists in the code: the command rebuilds the autoload map. When the error persists, check that the file name and the class name match in uppercase and lowercase too: on Linux, case matters, even when the code worked on your development machine.

A Laravel deployment has three parts: a web server that serves only the public directory and passes all other requests to PHP-FPM, background queue workers running under Supervisor, and one cron entry that runs the scheduler every minute. You can build and test the cron entry with the Cron expression generator, and restart the services with systemctl. Limits such as upload size and memory are set in the php.ini directives, and Redis is a good fit for the cache, sessions, and queues. When the database connection fails, the fixes are on the Common MySQL errors page.

For updates without downtime, use the release directories pattern: each deployment goes into a new directory under releases, where you run composer, the Vite build, and the cache commands. The storage directory and the .env file are shared by all releases and linked into each new directory. Finally, you switch a symbolic link named current to the new release. The web server's document root points to current/public, and to roll back to a previous release, you just switch the link back. After the switch, run php artisan reload, so the queue workers start with the new code. In an application that runs on Laravel Octane, the code stays in memory between requests, so it also needs a restart on every deployment, and reload handles that too. An application that runs its queues on Redis can use Laravel Horizon, which manages the queue workers and provides a dashboard.

The domain names, paths, the deploy user name, and the PHP-FPM socket path on this page are examples, so replace them with your server's values. More web server settings are on the Nginx cheat sheet and the Apache cheat sheet, and fixes for 502 and 504 errors on the PHP-FPM side are on the 500, 502, 503, and 504 server errors page.

Did you know?

On a Laravel VPS, the server comes ready to work: PHP, Composer, Redis, Supervisor for queues, and Node.js for building the CSS and JavaScript files are installed and configured, cron is ready to run the scheduler, and FrankenPHP with Laravel Octane, along with Caddy with a WAF and automatic HTTPS, come preinstalled. You get full root access over SSH, so you run the deployment steps yourself. To build the environment from scratch, with Nginx or Apache, a Linux VPS with full root access and guaranteed resources is the right fit.

Laravel VPS plans

Laravel in production FAQ

Can I run a Laravel application with queues and a task scheduler on a VPS?

Yes. A VPS gives you full root access, so you run the queue workers under Supervisor, which restarts them after a crash and after a reboot, and add one cron entry that runs the scheduler every minute. On a Laravel VPS, these components, including Supervisor, Redis, and cron, are already installed and configured when the server is handed over to you.

What should I check before deploying a Laravel application to production?

In the .env file, set APP_ENV=production and APP_DEBUG=false, and make sure APP_KEY is set and APP_URL starts with https. On the server, install the dependencies with composer install --no-dev --optimize-autoloader, build the assets with npm run build, run php artisan migrate --force and php artisan optimize, and give the PHP-FPM user write access to the storage and bootstrap/cache directories. The web server serves only the public directory.

Why doesn't a change to the .env file show up on the site?

After php artisan config:cache or php artisan optimize, Laravel loads the configuration from the cache file and doesn't read .env. That's why you run php artisan optimize again after every change to .env. Queue workers load the configuration once, so restart them too, with php artisan queue:restart.

How do I update a Laravel application on the server without downtime?

Upload each release to a new directory, run the installation, the build, and the cache commands in it, and finally switch a symbolic link named current to the new release. The document root points to current/public, so the switch is instant, and to roll back to the previous release, you just switch the link back. For a short update in the same directory, you can use maintenance mode with php artisan down --render="errors::503", which shows visitors a proper page until php artisan up.

How do I keep Laravel queues running in the background?

With Supervisor. In a program file, set the php artisan queue:work command, the number of processes in numprocs, and the user that runs them, and Supervisor starts the processes when the server boots and restarts them right away if they stop. On every deployment, run php artisan queue:restart, and the workers start again with the new code.

Shopping cart

Your cart is emptyYou can start with one of our popular plans.

Site search

Accessibility

Text size
100%
Accessibility statement