Square CloudSquare Cloud

How to host a PHP (Laravel) application

To host a Laravel application, set APP_KEY and the production variables, run composer install --no-dev and cache the configuration. Then apply migrations and serve the public/ folder with PHP-FPM and nginx, or with a PHP server behind a proxy.

Updated 8 min read

Learning objectives

After reading this article you will be able to:

  • Prepare the production .env, the APP_KEY and the Composer dependencies
  • Choose between PHP-FPM with nginx and PHP's built-in server
  • Run migrations, queues and the scheduler, and fix the most common 500 errors
On this page

A Laravel app that runs fine on your laptop leans on things that only exist there: the development .env, Composer's dev packages, the Vite dev server and a storage/ folder anyone can write to. In production, each of those pieces has to be prepared, or the result is a 500 error with no explanation.

This guide follows the order of a real deploy and ends with the most common errors. For the big picture of shipping any backend, see how to host an API.

What changes in the production .env?#

Laravel reads its configuration from environment variables, usually from the .env file. The production minimum:

bash
APP_NAME=MyApp
APP_ENV=production
APP_KEY=base64:paste_the_generated_key_here
APP_DEBUG=false
APP_URL=https://myapp.example.com

LOG_CHANNEL=stderr
LOG_LEVEL=info

DB_CONNECTION=mysql
DB_URL=mysql://user:password@db-host:3306/myapp
  • APP_KEY: encrypts cookies, sessions and everything that goes through Crypt. Generate one with php artisan key:generate --show, which prints a new key without touching any file, and store it as a secret. Changing the key ends every session and makes whatever was encrypted with the old one unreadable; to rotate it without that effect, list the old key in APP_PREVIOUS_KEYS.
  • APP_DEBUG=false: with debug on, the error page shows configuration values and code to any visitor, and Laravel's docs say it should always be false in production.
  • LOG_CHANNEL=stderr: the stderr channel ships in config/logging.php and sends logs to the process output, where your host shows them; a file in storage/logs works on a VPS but disappears from view inside a container.
  • DB_URL: the connections in config/database.php accept a single URL instead of host, user and password in separate variables.

The production .env never goes into Git: on a VPS it lives on the server, on a platform it becomes the app's environment variables. See what a .env file is.

How do you install, cache and migrate on each deploy?#

Dependencies and caches#

bash
composer install --no-dev --optimize-autoloader
php artisan optimize

--no-dev skips the require-dev packages (tests, debug tools), and --optimize-autoloader turns PSR-4 rules into a classmap. Composer's docs say to always enable this optimization in production and never in development.

php artisan optimize caches configuration, events, routes and views in one go (the individual commands are config:cache, event:cache, route:cache and view:cache). Once the configuration is cached, Laravel stops loading .env, and every env() call outside the config/ files returns null. Read values in code with config('services.stripe.key'), never env('STRIPE_KEY'). When a variable changes, run optimize again; php artisan optimize:clear removes every cache.

Migrations#

bash
php artisan migrate --force

In production, Laravel asks for confirmation before running migrations, and an automated deploy has nobody to answer: --force skips the prompt. If the app runs on more than one server, --isolated takes a lock so only one of them runs the migrations.

Run migrations before the new code takes traffic and write changes the previous code can live with: add the column in one deploy and start requiring it in the next. The full topic is in migrations on deploy.

Which server: PHP-FPM with nginx or the built-in server?#

Every request has to reach public/index.php: Laravel's docs warn that serving the app from the project root exposes .env and other sensitive files. There are two common setups.

PHP-FPM with nginx on a VPS#

nginx takes the HTTP request, serves static files directly and hands PHP to PHP-FPM, which keeps a pool of worker processes. The core of the example in Laravel's docs:

nginx
server {
    listen 80;
    server_name myapp.example.com;
    root /srv/myapp/public;

    index index.php;
    charset utf-8;

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

    location ~ ^/index\.php(/|$) {
        # point this at the PHP-FPM socket installed on your server
        fastcgi_pass unix:/run/php/php-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_hide_header X-Powered-By;
    }

    location ~ \.php$ {
        return 404;
    }

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

HTTPS is handled by nginx (with a Let's Encrypt certificate, for example) or by a reverse proxy in front of it.

PHP's built-in server behind a proxy#

php artisan serve starts PHP's built-in server already pointed at public/: one process, no nginx or PHP-FPM to configure.

bash
PHP_CLI_SERVER_WORKERS=4 php artisan serve --host=0.0.0.0 --port="${PORT:-8000}" --no-reload

The PHP manual says this server is designed to aid development, isn't a full-featured web server and shouldn't be used on a public network. It runs a single process by default: one slow request holds up the rest. The PHP_CLI_SERVER_WORKERS variable forks several workers (not on Windows), and Laravel's serve only honors it together with --no-reload. Without --host=0.0.0.0, it listens on 127.0.0.1 and the site looks down.

The setup that respects those limits is the server behind a proxy that faces the internet and terminates HTTPS, with several workers and moderate traffic. For more load, move to PHP-FPM with nginx or to FrankenPHP, which Laravel's docs also cover.

Behind any proxy that terminates HTTPS, Laravel may generate http:// links, because the request reaches it over plain HTTP. The documented fix is to trust the proxy in bootstrap/app.php:

php
->withMiddleware(function (Middleware $middleware): void {
    $middleware->trustProxies(at: '*');
})

Only use '*' when the app can't be reached without going through the proxy; otherwise, list the proxy's IPs.

How do you build the assets with Vite?#

bash
npm ci
npm run build

npm run build writes the versioned files and the manifest.json to public/build, which the @vite directive uses to render the <script> and <link> tags. If your server has no Node.js, run the build in CI and ship the public/build folder with the code, as shown in deploying with GitHub Actions. Variables prefixed with VITE_ are baked into the JavaScript at build time: changing one means building again.

Where should user uploads live?#

By default, uploads go to storage/app, on the server's disk. That breaks in three cases: when the disk is recreated on every deploy, when there is more than one instance (each sees only its own files) and when the disk fills up. On a single-instance VPS, the local disk plus php artisan storage:link is fine; anywhere else, use S3-compatible object storage:

bash
composer require league/flysystem-aws-s3-v3 --with-all-dependencies
bash
FILESYSTEM_DISK=s3
AWS_ACCESS_KEY_ID=your_key
AWS_SECRET_ACCESS_KEY=your_secret
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=my-bucket
AWS_ENDPOINT=https://your-provider-endpoint
AWS_USE_PATH_STYLE_ENDPOINT=false

For an S3-compatible service outside AWS, Laravel's docs say you usually only change AWS_ENDPOINT (and turn on AWS_USE_PATH_STYLE_ENDPOINT if the provider asks for it). The code stays the same: $request->file('photo')->store('photos') writes to the default disk.

How do you run queues and the scheduler?#

Queued jobs and scheduled tasks run outside the request, in separate processes:

bash
# queue worker: a long-running process
php artisan queue:work --tries=3 --max-time=3600

# scheduler: one crontab line, every minute
* * * * * cd /srv/myapp && php artisan schedule:run >> /dev/null 2>&1

The worker keeps the booted app in memory and won't see new code until it restarts: run php artisan queue:restart (or php artisan reload, which also restarts other long-running services) on every deploy. On a VPS, a process monitor such as Supervisor or systemd brings the worker back when it exits, including through --max-time, which caps its lifetime and frees accumulated memory.

Where there is no cron, php artisan schedule:work stays in the foreground and invokes the scheduler every minute (the docs present it for local use). To choose between cron, workers and queues, see cron vs workers vs queues.

Which errors show up after the deploy?#

No application encryption key has been specified. The APP_KEY never reached the process. Set the variable and, if you cache the configuration, run php artisan optimize again: the old cache holds the empty value.

A 500 error with this message in the log. The web server's user can't write to storage/ or bootstrap/cache, two folders Laravel needs to write to.

text
The stream or file "/srv/myapp/storage/logs/laravel.log" could not be opened in append mode: Failed to open stream: Permission denied

On a VPS, give ownership of those folders to the PHP-FPM user (chown -R www-data:www-data storage bootstrap/cache) instead of opening everything with chmod 777. With LOG_CHANNEL=stderr the log no longer depends on the folder, but sessions, cache and compiled views still write there.

Vite manifest not found at: /srv/myapp/public/build/manifest.json. The asset build didn't run, or the public/build folder was left out of the upload.

SQLSTATE[HY000] [2002] Connection refused. Laravel tried the database at 127.0.0.1: DB_URL or DB_HOST never reached the process, or the config cache kept the development value.

Links and forms on http:// while the site is on HTTPS. trustProxies is missing. If the proxy doesn't send the X-Forwarded-* headers, URL::forceScheme('https') in AppServiceProvider forces the scheme.

New routes return 404. The route cache is left over from the previous deploy. Run optimize on every deploy, not just the first.

To check the deploy, curl -i https://myapp.example.com/up should return 200: it's Laravel's default health route, which returns 500 if the app failed to boot. Before opening to the public, go through the API production checklist.

How to do this on Square Cloud#

On Square Cloud, the PHP runtime uses the built-in-server-behind-a-proxy setup: it already listens on port 80 and handles small and medium apps with no Nginx or PHP-FPM to configure, and the app is published over HTTPS on a *.squareweb.app subdomain. On every start, composer install runs with an optimized autoloader, and the image includes Node.js with npm for the asset build. Laravel, Symfony and plain PHP run this way. You upload the project as a ZIP in the dashboard, with the CLI, through GitHub or with the VS Code extension; the squarecloud.app file is optional, since the dashboard generates it on deploy.

There is no build step: the asset build goes in CI (ship the finished public/build) or in the start command (START), a shell command of up to 256 characters. A sample to adjust and test on your project, ending with the built-in server on the port in the PORT variable:

bash
npm ci && npm run build && php artisan migrate --force && php artisan optimize && php artisan serve --host=0.0.0.0 --port=$PORT

The keys from your production .env become the app's environment variables (the dashboard imports a .env), apply on the next restart and already exist during the install: COMPOSER_NO_DEV=1, which Composer reads as --no-dev, should leave require-dev out (check the install output in the logs). If links come out as http://, apply trustProxies. A web app uses at least 512 MB of the plan's RAM; Hobby starts at R$12.49 a month, with 1 GB.

The disk persists across deploys, but each app has its own. For uploads, Blob has an S3-compatible API (endpoint https://s3-blob.squarecloud.app, region auto, bucket public or private) for AWS_ENDPOINT. For the queue worker or schedule:work, one approach to test is a second app with no subdomain, the same code, the same variables and the command as its START, from 256 MB; the queue then needs a driver that lives off the disk, such as the database or Redis. MySQL and PostgreSQL hosting starts on Standard, from R$44.99 a month, with TLS required: on MySQL, point MYSQL_ATTR_SSL_CA at the certificate you download from the dashboard. See the details of PHP hosting.

API hosting

APIs in always-on containers, with no cold starts

PHP hosting

FAQs

What happens if I change the APP_KEY?

Every session ends and data encrypted with the old key can no longer be read, because Laravel encrypts cookies and Crypt values with it. To rotate it without that effect, list the previous key in APP_PREVIOUS_KEYS.

Can I use php artisan serve in production?

It runs PHP's built-in server, which the PHP manual says is designed for development and shouldn't be used on a public network, with a single process by default. Behind a proxy with HTTPS and with more workers, it handles moderate traffic; for heavier traffic, move to PHP-FPM with nginx or FrankenPHP.

Why does env() return null after config:cache?

Once the configuration is cached, Laravel no longer loads the .env file, and env() outside the config/ files returns null. Read values in code with config() and rebuild the cache whenever a variable changes.

Do I need Node.js on the server for Vite?

Only if the asset build runs on the server. The alternative is to run npm run build in CI and ship the finished public/build folder, with the manifest.json that the @vite directive reads.

Next articleHow to host a Go APITo host a Go API, read the port from PORT, listen on 0.0.0.0, build a binary for the server's OS and handle SIGTERM with a graceful shutdown. Full code included.