How to Deploy Laravel with Docker on a VPS: Complete Production Guide
Step-by-step tutorial to deploy Laravel 11 with Docker on a VPS. Includes production docker-compose.yml for PHP-FPM, Nginx, MySQL, Redis, and Horizon queue workers.

Introduction
You have a Laravel application that works perfectly on your local machine. Now you need to deploy it — and shared hosting won't cut it anymore. You need Redis for caching, Horizon for queue workers, a specific PHP version with custom extensions, and the ability to scale when your client's traffic grows.
On shared hosting, your Laravel app runs alongside dozens of other accounts fighting for the same PHP-FPM pool. Memory limits are hard-capped at 256 MB or 512 MB. You can't install Redis. Queue workers are simulated with cron jobs that run every minute. And if you need imagick for image processing or pdo_sqlsrv for a client's legacy database, you're out of luck — shared hosting doesn't install custom extensions.
Docker on a VPS changes all of this. Your Laravel app gets its own isolated PHP-FPM container with exactly the extensions it needs. Redis runs as a dedicated service. Horizon processes jobs in real time. MySQL gets a persistent volume that survives container restarts. And when you need to deploy a second application with a different PHP version, you spin up a new set of containers — no conflicts, no compromises.
This guide walks you through deploying a production-ready Laravel application with Docker Compose. By the end, you'll have a full stack running on your VPS: Nginx serving requests, PHP-FPM running your app, MySQL for persistence, Redis for cache and queues, and Horizon processing background jobs. Every configuration is battle-tested and ready for real traffic.
If you're evaluating whether Docker is right for your setup, read our Docker vs Virtual Machines comparison first — it covers the decision framework and VPS plan sizing. If you're still on shared hosting and considering the move, our Laravel on Shared Hosting guide details the limitations that Docker solves.
1. Architecture Overview
Each component of your Laravel stack runs in its own Docker container, connected by a custom bridge network. Here's what the production stack looks like:
| Container | Image | Role | Ports |
|---|---|---|---|
| app | Custom PHP-FPM 8.2 Alpine | Runs Laravel, handles PHP requests | 9000 (internal) |
| web | nginx:1.27-alpine | Reverse proxy, static files, SSL termination | 80, 443 |
| db | mysql:8.0 | Persistent database | 3306 (internal) |
| redis | redis:7-alpine | Cache, sessions, queue driver | 6379 (internal) |
| horizon | Custom (same image as app) | Queue worker running php artisan horizon |
none |
The flow is straightforward: a request hits Nginx on port 80 or 443, Nginx forwards PHP requests to the app service on port 9000 via FastCGI, and the Laravel application communicates with MySQL (db:3306) and Redis (redis:6379) over the internal Docker network. Horizon polls the same Redis instance for queued jobs.

Only Nginx exposes ports to the outside world. MySQL and Redis are accessible only within the Docker network — no external connections can reach them directly. This is significantly more secure than a shared hosting environment where your database is accessible from any script on the server.
2. Dockerfile — PHP-FPM Container
The foundation of your stack is a custom PHP-FPM image with the exact extensions Laravel needs. We'll use a multi-stage build to keep the production image lean — installing build dependencies in one stage and copying only what's needed to the production image.
# Stage 1: Build
FROM php:8.2-fpm-alpine AS build
# Install build dependencies
RUN apk add --no-cache --virtual .build-deps \
$PHPIZE_DEPS \
curl-dev \
libpng-dev \
libjpeg-turbo-dev \
libwebp-dev \
freetype-dev \
oniguruma-dev \
sqlite-dev \
libxml2-dev \
libzip-dev \
linux-headers
# Install PHP extensions
RUN docker-php-ext-install \
bcmath \
curl \
exif \
gd \
mbstring \
pdo \
pdo_mysql \
pdo_sqlite \
xml \
zip
# Install Redis extension via PECL
RUN pecl install redis && docker-php-ext-enable redis
# Install Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
WORKDIR /var/www/html
# Copy composer files first (layer caching)
COPY composer.json composer.lock ./
RUN composer install --no-dev --no-scripts --no-autoloader --optimize-autoloader
# Copy rest of application
COPY . .
# Run composer scripts now that app is copied
RUN composer dump-autoload --optimize --no-dev
# Stage 2: Production
FROM php:8.2-fpm-alpine AS production
# Install runtime dependencies only
RUN apk add --no-cache \
curl \
libpng \
libjpeg-turbo \
libwebp \
freetype \
oniguruma \
libxml2 \
libzip \
fcgi
# Copy extensions from build stage
COPY --from=build /usr/local/lib/php/extensions /usr/local/lib/php/extensions
COPY --from=build /usr/local/etc/php/conf.d /usr/local/etc/php/conf.d
# Copy the application
COPY --from=build /var/www/html /var/www/html
# Create non-root user
RUN addgroup -g 1000 laravel && \
adduser -D -u 1000 -G laravel laravel && \
chown -R laravel:laravel /var/www/html
USER laravel
WORKDIR /var/www/html
What each stage does:
The build stage installs compiler toolchains ($PHPIZE_DEPS) and development headers needed to compile PHP extensions from source. It installs Composer, pulls in PHP dependencies, and generates the optimized autoloader. None of these build tools make it to the final image.
The production stage copies only the compiled extensions and the application code. It installs just the runtime libraries (not the -dev headers). A non-root laravel user is created with ID 1000 — matching the host user for clean file permissions on mounted volumes. The container runs as this user, not root.
The result: a production image roughly 120-150 MB (versus 400+ MB without multi-stage) with no development tools, no Composer, and no unnecessary attack surface.
PHP-FPM Configuration
Add a php-fpm.d/zz-custom.conf override to optimize for production:
[www]
; Catch workers output (useful for debugging)
catch_workers_output = yes
; Clear environment (security: don't pass host env vars to PHP)
clear_env = yes
; Process manager — dynamic balances memory and performance
pm = dynamic
pm.max_children = 20
pm.start_servers = 4
pm.min_spare_servers = 2
pm.max_spare_servers = 10
; Slow log for debugging
slowlog = /proc/self/fd/2
request_slowlog_timeout = 10s
; Security: limit extensions
security.limit_extensions = .php
These settings are tuned for a 2-4 GB RAM container environment. Adjust pm.max_children up if your VPS has more RAM — each PHP-FPM child typically consumes 30-50 MB.
OPcache Configuration
Create an opcache.ini file for production:
; Enable OPcache
opcache.enable=1
opcache.revalidate_freq=0
opcache.validate_timestamps=0
opcache.max_accelerated_files=10000
opcache.memory_consumption=128
opcache.interned_strings_buffer=16
opcache.fast_shutdown=1
opcache.enable_cli=1
With validate_timestamps=0, OPcache never checks if files changed on disk — perfect for Docker where the image is immutable. When you deploy a new version, you rebuild the image rather than patching files in place.
3. Nginx Configuration
Nginx sits in front of PHP-FPM, serving static files directly and proxying PHP requests to the app container:
server {
listen 80;
server_name yourdomain.com;
root /var/www/html/public;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
index index.php;
charset utf-8;
# Gzip compression
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript;
gzip_min_length 1000;
gzip_proxied any;
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; }
# Block access to dot files
location ~ /\.(?!well-known) {
deny all;
}
# Pass PHP requests to the app container
location ~ \.php$ {
fastcgi_pass app:9000;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_buffer_size 128k;
fastcgi_buffers 4 256k;
fastcgi_busy_buffers_size 256k;
fastcgi_read_timeout 300;
}
# Cache static assets
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
error_page 404 /index.php;
}
The critical line is fastcgi_pass app:9000. In Docker Compose, service names resolve to container IPs via the internal DNS server. Nginx doesn't need to know the PHP-FPM container's IP — it simply connects to app:9000 and Docker routes the traffic. This is why you name services descriptively: they become hostnames within the Docker network.
Mount this file at /etc/nginx/conf.d/default.conf inside the Nginx container. The clean separation — Nginx handles HTTP, PHP-FPM handles PHP — mirrors how you'd configure a native setup, but with the benefit that each service can be scaled or restarted independently.
4. Docker Compose — Full Production Stack
Here is the complete docker-compose.yml. Every service includes health checks, restart policies, resource limits, and logging with rotation:
version: "3.8"
services:
# Laravel PHP-FPM application
app:
build:
context: .
target: production
container_name: laravel_app
restart: unless-stopped
working_dir: /var/www/html
volumes:
- .env:/var/www/html/.env:ro
- app_storage:/var/www/html/storage
depends_on:
db:
condition: service_healthy
redis:
condition: service_healthy
networks:
- laravel_network
healthcheck:
test: ["CMD", "php-fpm-healthcheck"]
interval: 10s
timeout: 5s
retries: 3
start_period: 15s
deploy:
resources:
limits:
cpus: "1.0"
memory: 512M
reservations:
cpus: "0.5"
memory: 256M
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
# Nginx web server
web:
image: nginx:1.27-alpine
container_name: laravel_web
restart: unless-stopped
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx/conf.d:/etc/nginx/conf.d:ro
- app_storage:/var/www/html/storage:ro
- ./public:/var/www/html/public:ro
- ./certbot/www:/var/www/certbot:ro
- ./certbot/conf:/etc/letsencrypt:ro
depends_on:
app:
condition: service_healthy
networks:
- laravel_network
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s
deploy:
resources:
limits:
cpus: "0.5"
memory: 128M
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
# MySQL database
db:
image: mysql:8.0
container_name: laravel_db
restart: unless-stopped
environment:
MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
MYSQL_DATABASE: ${DB_DATABASE}
MYSQL_USER: ${DB_USERNAME}
MYSQL_PASSWORD: ${DB_PASSWORD}
volumes:
- db_data:/var/lib/mysql
- ./docker/mysql/my.cnf:/etc/mysql/conf.d/my.cnf:ro
networks:
- laravel_network
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${DB_ROOT_PASSWORD}"]
interval: 10s
timeout: 5s
retries: 5
start_period: 30s
deploy:
resources:
limits:
cpus: "2.0"
memory: 1024M
reservations:
cpus: "1.0"
memory: 512M
logging:
driver: "json-file"
options:
max-size: "20m"
max-file: "5"
# Redis cache & queue
redis:
image: redis:7-alpine
container_name: laravel_redis
restart: unless-stopped
command: redis-server --appendonly yes --maxmemory 256mb --maxmemory-policy allkeys-lru
volumes:
- redis_data:/data
networks:
- laravel_network
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 3
deploy:
resources:
limits:
cpus: "0.5"
memory: 256M
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
# Laravel Horizon queue worker
horizon:
build:
context: .
target: production
container_name: laravel_horizon
restart: unless-stopped
command: php artisan horizon
volumes:
- .env:/var/www/html/.env:ro
- app_storage:/var/www/html/storage
depends_on:
db:
condition: service_healthy
redis:
condition: service_healthy
networks:
- laravel_network
deploy:
resources:
limits:
cpus: "1.0"
memory: 512M
reservations:
cpus: "0.5"
memory: 256M
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
networks:
laravel_network:
driver: bridge
volumes:
app_storage:
driver: local
db_data:
driver: local
redis_data:
driver: local
Key production details in this compose file:
-
restart: unless-stopped— containers restart automatically after crashes or host reboots, but won't restart if you intentionally stop them withdocker compose stop. For Horizon, this is critical — if the queue worker crashes at 3 AM, it comes back automatically. -
Health checks with
depends_onconditions — theappcontainer waits until MySQL and Redis are healthy before starting. This prevents the "MySQL connection refused" race condition that happens when PHP-FPM starts before the database is ready. Thestart_periodgives MySQL 30 seconds to initialize on first boot. -
Resource limits — each container gets explicit CPU and memory bounds. Without these, a memory leak in PHP-FPM could consume all available RAM and crash the host. The
reservationsfield tells Docker to guarantee minimum resources to each container. -
Log rotation — JSON-file logging with size limits prevents disk exhaustion. The
max-size: "10m"andmax-file: "3"options keep at most 30 MB of logs per container. For higher-traffic apps, ship logs to an external service. -
Named volumes —
db_data,redis_data, andapp_storagepersist data across container restarts, rebuilds, and even complete stack teardowns. Theapp_storagevolume holds your Laravelstorage/directory (logs, cache, uploaded files), so user uploads survive container rebuilds.
5. Environment Configuration
Docker networking changes how your .env file references services. Instead of localhost, you use Docker service names:
# .env.production
APP_NAME="Your Laravel App"
APP_ENV=production
APP_KEY=base64:... # Generate this: docker compose run --rm app php artisan key:generate --show
APP_DEBUG=false
APP_URL=https://yourdomain.com
LOG_CHANNEL=stack
LOG_LEVEL=warning
# Database — Docker service name, not localhost
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=laravel_user
DB_PASSWORD=your_secure_password
DB_ROOT_PASSWORD=your_root_password
# Redis — Docker service name
REDIS_HOST=redis
REDIS_PASSWORD=null
REDIS_PORT=6379
# Cache / Session
CACHE_DRIVER=redis
SESSION_DRIVER=redis
# Queue
QUEUE_CONNECTION=redis
# Mail
MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
The DB_HOST=db and REDIS_HOST=redis lines are where most first-time Docker users trip. Docker Compose creates an internal DNS server that resolves service names to container IPs. Inside the laravel_network bridge, db resolves to the MySQL container's IP — transparently, with no configuration required.
Mount this file as a read-only volume (:.env:ro) so the container can read it but processes inside the container can't modify it. For secrets like database passwords, consider Docker secrets (Swarm mode) or a tool like HashiCorp Vault for larger deployments.
Generate the application key after the app container builds:
docker compose build app
docker compose run --rm app php artisan key:generate --show
Copy the output into your .env.production file under APP_KEY. Never run key:generate on a running production app — it would invalidate all existing sessions and encrypted data.
6. Deployment Steps
With all the configuration in place, here's the deployment sequence:
Step 1: Clone your project on the VPS
ssh user@your-vps-ip
mkdir -p /opt/apps/your-laravel-app
cd /opt/apps/your-laravel-app
git clone https://github.com/yourorg/your-laravel-app.git .
Step 2: Create the environment file
cp .env.example .env.production
# Edit .env.production with the values from Section 5
vim .env.production
Copy the configuration files into place:
mkdir -p nginx/conf.d docker/mysql
# Place your default.conf in nginx/conf.d/
# Place your my.cnf in docker/mysql/
Step 3: Build the app image
docker compose build app
This runs the multi-stage Dockerfile. The first build takes 2-3 minutes on a typical VPS. Subsequent builds are faster thanks to Docker layer caching — only changed layers are rebuilt.
Step 4: Start the database first
docker compose up -d db redis
Starting the database and Redis first lets them initialize before PHP-FPM tries to connect. Wait for the health checks to pass:
docker compose ps
# Verify db and redis show "healthy" in the STATUS column
Step 5: Run migrations and seed
docker compose run --rm app php artisan migrate --force
docker compose run --rm app php artisan db:seed --force # if you use seeders
The --force flag is required in production (Laravel won't run migrations without it outside local environment).
Step 6: Start the full stack
docker compose up -d
Step 7: Verify everything is running
docker compose ps
Expected output:
NAME STATUS PORTS
laravel_app Up 30 seconds (healthy) 9000/tcp
laravel_web Up 30 seconds (healthy) 0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp
laravel_db Up 45 seconds (healthy) 3306/tcp
laravel_redis Up 45 seconds (healthy) 6379/tcp
laravel_horizon Up 20 seconds (healthy)
All five containers should show (healthy). If any show (unhealthy) or (health: starting), check the logs:
docker compose logs app
docker compose logs web
Visit http://your-vps-ip in a browser. You should see your Laravel application. If you see a 502 Bad Gateway, the app container likely isn't healthy yet — wait 15 seconds and refresh.
7. SSL with Let's Encrypt
For HTTPS, use Certbot in standalone mode. This approach keeps SSL termination clean without adding another container to your stack.
Initial certificate
Stop Nginx temporarily (Certbot needs port 80):
docker compose stop web
Install Certbot on the host (not in Docker):
sudo apt update && sudo apt install -y certbot
Request the certificate:
sudo certbot certonly --standalone -d yourdomain.com -d www.yourdomain.com
Certbot validates domain ownership by spinning up a temporary web server on port 80, then places certificates in /etc/letsencrypt/live/yourdomain.com/.
Mount certificates into Nginx
Update the Nginx configuration to listen on 443 and reference the certificates:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name yourdomain.com www.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
# ... rest of the location blocks from Section 3
}
Update the web service in docker-compose.yml to mount the certificate directory:
web:
volumes:
- /etc/letsencrypt:/etc/letsencrypt:ro
Restart Nginx:
docker compose restart web
Auto-renewal
Add a cron job on the host:
sudo crontab -e
0 3 * * * certbot renew --quiet --pre-hook "cd /opt/apps/your-laravel-app && docker compose stop web" --post-hook "cd /opt/apps/your-laravel-app && docker compose start web"
This stops Nginx at 3 AM daily, renews certificates if they're within 30 days of expiry, and restarts Nginx. The downtime is under 5 seconds — invisible to users.
For a zero-downtime alternative, use the DNS-01 challenge with your DNS provider's API, or deploy Traefik as a reverse proxy that handles certificates automatically. For agencies managing multiple apps on one VPS, Traefik is the better long-term choice — it eliminates the cert-per-app headache.
8. Laravel Horizon Queue Workers
Horizon processes background jobs: sending emails, generating reports, processing uploads, calling external APIs. In Docker, Horizon runs as a separate container that shares the same image as your app service — same code, same environment, different entry point.
The horizon service in the compose file above already handles the basics. For production, add a Horizon-specific health check:
horizon:
healthcheck:
test: ["CMD", "php", "artisan", "horizon:status"]
interval: 30s
timeout: 10s
retries: 3
start_period: 20s
php artisan horizon:status exits with code 0 if Horizon is running, non-zero if it's stopped or crashed. Combined with restart: unless-stopped, this ensures Horizon recovers from any failure automatically.
Scaling Horizon workers
If your queue grows faster than a single Horizon container can process, scale horizontally:
docker compose up -d --scale horizon=3
This runs three identical Horizon containers, all pulling jobs from the same Redis queue. Each container processes jobs independently — Redis handles the coordination.
For more granular control, edit config/horizon.php to define separate worker pools:
'environments' => [
'production' => [
'supervisor-1' => [
'maxProcesses' => 10,
'balanceMaxShift' => 1,
'balanceCooldown' => 3,
],
],
],
When to run Horizon outside Docker
For high-throughput queues (100,000+ jobs/day), running Horizon directly on the host can reduce latency by 5-10 ms per job — no container network overhead for Redis communication. The trade-off is losing the isolation and restart guarantees that Docker provides. Most Laravel applications won't notice the difference; benchmark your specific workload before making this decision.
9. Production Hardening Checklist
Before you point real traffic at your deployment, work through this checklist:
-
Non-root user — your Dockerfile sets
USER laravelwith UID 1000. Verify:docker compose exec app whoamishould outputlaravel. -
Read-only filesystem — add
read_only: trueto theappservice in docker-compose.yml, then explicitly mark writable directories withtmpfsmounts for/tmpand thestorage/volume. This prevents attackers from writing to the container filesystem even if they achieve code execution. -
Resource limits enforced — run
docker statsand confirm each container shows the memory limit you configured. A container consuming its full allocation without crashing confirms limits are working. -
Log rotation verified — check
/var/lib/docker/containers/*/and confirm no single log file exceeds 10 MB. Rundocker compose logs --tail=50 appto verify logging is functional. -
Regular image updates — schedule
docker compose pull && docker compose up -dweekly to pull updated base images (security patches for PHP, Nginx, MySQL, Redis). Alpine-based images minimize the update surface — typically just a few MB. -
Database backups automated — create a host-level cron job that dumps the database and syncs it off-server:
#!/bin/bash
# /opt/scripts/backup-db.sh
docker compose exec -T db mysqldump -u root -p"${DB_ROOT_PASSWORD}" laravel \
| gzip > /backups/laravel_$(date +%Y%m%d_%H%M).sql.gz
# Sync to remote storage
rsync -az /backups/ backup@offsite-server:/backups/
-
Network isolation confirmed —
docker compose exec app nc -zv db 3306should succeed (internal access), butnc -zv your-vps-ip 3306from your local machine should fail. MySQL and Redis ports are not exposed externally — only Nginx listens on the host. -
.envnot in the image — the.envfile is mounted as a volume at runtime, not copied during the Docker build. Rundocker compose run --rm app ls -la .envto confirm it's present (mounted), thendocker run --rm your-image ls -la .envto confirm it's absent from the image itself. -
Health checks passing — all five containers should show
(healthy)indocker compose ps. Set up monitoring (Uptime Kuma, Better Stack, or a simple cron ping) to alert you if health checks fail.
10. DreamHost VPS Sizing Guide
Choosing the right VPS plan depends on how many applications you're running and their traffic levels. This table maps Docker container density to DreamHost plans:
| Plan | vCPU | RAM | Storage | Price (₹/mo) | Laravel Apps | Concurrent WP Sites | Best For |
|---|---|---|---|---|---|---|---|
| Cloud Server 4G | 2 Core | 4 GB | 40 GB SSD | ₹499 | 1 app | 5-10 | Solo developer, single project |
| KVM 8G | 2 Core | 8 GB | 160 GB SSD | ₹1,200 | 3-5 apps | 15-25 | Small agency, multiple client projects |
| KVM 16G | 4 Core | 16 GB | 240 GB SSD | ₹2,400 | 5-10 apps | 25-50 | Growing agency, staging environments |
| KVM 32G | 8 Core | 32 GB | 480 GB SSD | ₹4,800 | 15-25 apps | 50-100 | Large agency, CI/CD pipelines |
How we calculated app capacity: Each Laravel app running the full Docker stack described in this guide consumes approximately:
- PHP-FPM: 256-512 MB (depends on
pm.max_children) - Nginx: 64-128 MB (mostly static file cache)
- MySQL: 512 MB - 1 GB (InnoDB buffer pool)
- Redis: 128-256 MB
- Horizon: 128-256 MB
That's roughly 1-2 GB per Laravel application stack. With an 8 GB VPS, reserve 1 GB for the OS and Docker daemon, leaving 7 GB — enough for 3-5 production Laravel applications, or a mix of Laravel and WordPress sites.
All DreamHost KVM plans are Docker-ready with full root access, Mumbai datacenter for low latency across India, and flat pricing that stays the same year after year. No intro discounts that double on renewal. No mandatory multi-year contracts.
If you run both Laravel and WordPress, they coexist cleanly on the same VPS — each gets its own containers with isolated PHP versions and databases. Use Traefik or Nginx Proxy Manager as a reverse proxy to route domains to the correct container. See our Docker vs Virtual Machines guide for the full hybrid approach pattern.
Troubleshooting
"No application encryption key" on first load
The .env file doesn't have APP_KEY set, or the key wasn't properly mounted. Generate it:
docker compose run --rm app php artisan key:generate --show
Copy the output into your .env file and restart: docker compose restart app.
502 Bad Gateway
Nginx can't reach PHP-FPM. Check the app container status:
docker compose logs app --tail=20
Common causes:
- The
appcontainer crashed due to a syntax error in your code. Fix the error, rebuild:docker compose build app && docker compose up -d app. - The
.envfile has incorrect database credentials, causing Laravel to crash on startup. Checkdocker compose logs appforSQLSTATE[HY000]errors. - PHP-FPM isn't listening on port 9000. Verify the
appcontainer's command is the default FPM entrypoint — overridingcommand:in docker-compose.yml will replace the FPM process.
MySQL connection refused (SQLSTATE[HY000] [2002])
The app container started before MySQL was ready. The depends_on with condition: service_healthy should prevent this, but if it happens:
docker compose logs db --tail=20
If MySQL is still initializing (first run), wait 30-60 seconds for the start_period to complete. If it's failing, check that DB_ROOT_PASSWORD in your .env matches the MYSQL_ROOT_PASSWORD in docker-compose.yml.
Permission denied on storage/
The app_storage volume has wrong ownership. The container runs as UID 1000 (laravel user), but the volume directory might be owned by root:
docker compose run --rm --user root app chown -R laravel:laravel /var/www/html/storage
docker compose run --rm app php artisan storage:link
Horizon not processing jobs
Check if Horizon is running:
docker compose logs horizon --tail=10
If the container shows (unhealthy) or Exited, check for PHP errors in the logs. Common issues: Redis not running (Horizon can't connect to the queue), or the Redis host in .env is still set to 127.0.0.1 instead of redis.
Container keeps restarting
docker compose ps
# Look for containers with Restarting status
docker compose logs <service-name> --tail=50
A restart loop usually means the container process exits immediately. Check the entrypoint, command, and any mounted volumes. For the app container, the default PHP-FPM entrypoint runs in the foreground — if you override command:, make sure whatever you run stays in the foreground (Horizon does, php artisan serve does, a bash script with exec at the end does).
Conclusion
You now have a production-ready Laravel deployment with Docker: Nginx serving requests, PHP-FPM handling your application, MySQL persisting data, Redis accelerating cache and queues, and Horizon processing background jobs — all running in isolated containers with health checks, resource limits, and automatic recovery from failures.
This stack gives you what shared hosting never can: root access, custom PHP extensions, real Redis for queue workers, and the ability to scale by adding containers or moving to a larger VPS. When your next client project needs PHP 8.3 with a specific set of extensions, you update one line in the Dockerfile, rebuild, and deploy — no server reconfiguration, no conflicts with existing applications, no downtime.
For further reading: if you're running multiple applications, set up a reverse proxy with Traefik or Nginx Proxy Manager to route domains to the correct containers. If you hit performance ceilings, our Docker vs Virtual Machines guide covers the hybrid approach — native MySQL for speed, containers for application isolation.
Ready to deploy? A DreamHost KVM VPS gives you full root access, Docker support out of the box, and Mumbai datacenter hosting for low latency across India — starting at ₹1,200/mo with flat pricing that never changes.
Frequently Asked Questions
What's the best way to deploy Laravel with Docker on a VPS?
Use Docker Compose with separate services for PHP-FPM, Nginx, and MySQL/PostgreSQL. Define your Laravel app as a PHP-FPM service using php:8.2-fpm image, serve it through an Nginx container, and connect to a dedicated database container.
Can I use Laravel Sail for production deployment?
Laravel Sail is designed for local development, not production. While you can reuse the docker-compose.yml that Sail generates, you should customize it with production settings: remove xdebug, add health checks, configure logging, and implement restart policies.
How do I handle environment variables for Laravel Docker containers?
Use a .env file loaded at runtime via docker compose. Never bake secrets into images. For production, consider Docker secrets or a .env.production file mounted as a volume.
How do I set up Laravel Horizon with Docker?
Add a separate horizon service in docker-compose.yml that runs php artisan horizon. Use depends_on for Redis. Configure restart: always to keep Horizon running. Consider running queue workers outside Docker for better resource control on production.
Can Docker run Laravel and WordPress on the same VPS?
Yes. Each gets its own containers with isolated PHP versions and databases. Use Traefik or Nginx Proxy Manager as a reverse proxy to route domains. A DreamHost KVM 8G plan (₹1,200/mo) handles 3-5 Laravel apps + 10-15 WordPress sites.
How do I migrate from shared hosting Laravel to Docker on VPS?
Export your database, create a docker-compose.yml, copy your app files, update .env for Docker networking, and point your domain to the new VPS. Root access gives you full control with no shared hosting limits.