Mastering Docker for Laravel: A Beginner's Guide to Setup

13 min readUpdated on

A Docker setup for Laravel development: PHP-FPM, Nginx, MySQL, Redis and MailHog in Compose, with a Makefile on top so nobody has to remember the long commands.

Introduction to Docker

Docker packages an application and its dependencies into containers. An image is the blueprint of a container, a Dockerfile builds it, Docker Compose runs several containers together, a volume keeps data outside the container and a network lets containers talk to each other.

Why Docker for Laravel?

What it gives a Laravel project:

  • Consistent environments: everyone runs the same PHP, MySQL and Redis versions
  • Easy onboarding: make setup (see the Makefile below) replaces installing everything by hand
  • Isolated services: PHP, Nginx, MySQL and Redis run in separate containers
  • Environment in version control: the Dockerfile and the Compose file are committed next to the code
  • No local dependency conflicts: each project can run its own PHP and MySQL versions

Getting Started

Creating a New Laravel Project with Docker

Clone the example repository:

bash
# Clone the example repository
git clone https://github.com/Dommmin/laravel-docker-deploy.git my-project
cd my-project

Project Structure

Docker configuration lives in docker/, separate from the application code:

project/
├── docker/                  # Docker configuration files
│   ├── php/                 # PHP configuration
│   │   ├── Dockerfile       # Instructions to build PHP image
│   │   ├── php.ini          # PHP settings
│   │   └── www.conf         # PHP-FPM settings
│   ├── nginx/               # Nginx configuration
│   │   └── conf.d/          # Server blocks
│   └── supervisord.conf     # Process manager config
├── docker-compose.yml       # Multi-container definition
├── Makefile                 # Helper commands
└── .env                     # Environment variables

Docker Configuration

Base PHP Image

The base is a custom PHP 8.4 FPM image from Docker Hub (dommin/php-8.4-fpm) with common PHP extensions, Composer, Node.js and npm, and Git.

Dockerfile Explained

The Dockerfile, with a comment on each step:

Dockerfile
# Use our custom PHP 8.4 FPM image as the base
FROM dommin/php-8.4-fpm:latest

ARG USER_ID=1000
ARG GROUP_ID=1000

# Copy our custom PHP and PHP-FPM configuration files
COPY docker/start.sh /usr/local/bin/start.sh
COPY docker/php/php.ini /usr/local/etc/php/conf.d/php.ini
COPY docker/php/www.conf /usr/local/etc/php-fpm.d/www.conf
COPY docker/supervisord.conf /etc/supervisor/supervisord.conf

# Switch to root user to perform privileged operations
USER root

RUN chmod +x /usr/local/bin/start.sh
RUN usermod -u ${USER_ID} www-data
RUN groupmod -g ${GROUP_ID} www-data

WORKDIR /var/www

# Switch back to non-root user for security
USER www-data

EXPOSE 9000

Docker Compose Services Explained

docker-compose.yml defines five services: app, nginx, mysql, redis and mailhog.

App Service (PHP Application)

yml
app:
  build:
    context: .  # Use the current directory as build context
    dockerfile: docker/php/Dockerfile
    args:
      # Pass host user/group IDs to avoid permission issues
      - USER_ID=${USER_ID:-1000}
      - GROUP_ID=${GROUP_ID:-1000}
  container_name: ${COMPOSE_PROJECT_NAME}_app
  command: ["sh", "-c", "/usr/local/bin/start.sh"]
  restart: unless-stopped
  working_dir: /var/www
  volumes:
    - ./:/var/www  # Mount project directory into container
    - ./docker/php/php.ini:/usr/local/etc/php/conf.d/custom.ini
    - ./docker/php/www.conf:/usr/local/etc/php-fpm.d/www.conf
    - ./docker/supervisord.conf:/etc/supervisor/supervisord.conf
    - .env:/var/www/.env
  networks:
    - laravel-network
  ports:
    - "5173:5173"  # Vite development server port
  depends_on:
    mysql:
      condition: service_healthy
    redis:
      condition: service_healthy

The app container mounts the whole project directory, so code changes apply without a rebuild. It waits for healthy MySQL and Redis, and supervisor runs PHP-FPM, Horizon and Vite inside it.

Nginx Service

yml
nginx:
  image: nginx:alpine
  container_name: ${COMPOSE_PROJECT_NAME}_nginx
  restart: unless-stopped
  ports:
    - "80:80"
  volumes:
    - ./:/var/www
    - ./docker/nginx/conf.d:/etc/nginx/conf.d
  depends_on:
    - app
  networks:
    - laravel-network

MySQL Service

yml
mysql:
  image: mysql:8.0
  container_name: ${COMPOSE_PROJECT_NAME}_mysql
  restart: unless-stopped
  environment:
    MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
    MYSQL_DATABASE: ${DB_DATABASE}
  command:
    - --character-set-server=utf8mb4
    - --collation-server=utf8mb4_unicode_ci
  healthcheck:
    test: [ "CMD", "mysqladmin", "ping", "-h", "localhost" ]
    interval: 10s
    timeout: 5s
    retries: 5
    start_period: 60s
  ports:
    - "127.0.0.1:3306:3306"
  volumes:
    - mysql_data:/var/lib/mysql
  networks:
    - laravel-network

The healthcheck is what condition: service_healthy in the app service waits for. Data lives in the mysql_data named volume. The official image creates only the database named in MYSQL_DATABASE; the test database is created by the setup-test-db Makefile target. MySQL and Redis are published on 127.0.0.1 only, so other machines on your network cannot reach them, and PHP-FPM's port 9000 is not published at all because Nginx reaches it over the Compose network.

Redis Service

yml
redis:
  image: redis:alpine
  container_name: ${COMPOSE_PROJECT_NAME}_redis
  restart: unless-stopped
  healthcheck:
    test: [ "CMD", "redis-cli", "ping" ]
    interval: 10s
    timeout: 5s
    retries: 5
    start_period: 60s
  ports:
    - "127.0.0.1:6379:6379"
  networks:
    - laravel-network

MailHog Service

yml
mailhog:
  image: mailhog/mailhog:v1.0.1
  container_name: ${COMPOSE_PROJECT_NAME}_mailhog
  restart: unless-stopped
  ports:
    - "1025:1025"  # SMTP port
    - "8025:8025"  # Web interface port
  volumes:
    - mailhog_data:/maildir
  networks:
    - laravel-network

Mail sent by the app is caught on port 1025 and readable at http://localhost:8025. MailHog is no longer maintained; Mailpit (axllent/mailpit) is a drop-in replacement on the same ports (1025 and 8025) if you prefer a maintained tool.

Nginx Configuration

The config lives in docker/nginx/conf.d/default.conf.

Basic Server Configuration

nginx
server {
    listen 80;
    listen [::]:80;
    server_name localhost;
    root /var/www/public;
    index index.php;

    # Logging configuration
    access_log /var/www/storage/logs/nginx_access.log;
    error_log /var/www/storage/logs/nginx_error.log;

    charset utf-8;
    client_max_body_size 100M;
    client_body_buffer_size 128k;
}

root points at Laravel's public/ directory, and client_max_body_size 100M sets the upload limit.

Static File Caching

nginx
# Cache static files
location ~* \.(?:ico|css|js|gif|jpe?g|png|woff2?|eot|ttf|svg|otf)$ {
    expires 1y;
    access_log off;
    add_header Cache-Control "public, no-transform";
    add_header X-Content-Type-Options "nosniff";
    try_files $uri =404;
}

Static assets are cached for a year (expires 1y) and kept out of the access log.

PHP Processing

nginx
location ~ \.php$ {
    try_files $uri =404;
    include fastcgi_params;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass app:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
    fastcgi_param DOCUMENT_ROOT $realpath_root;
    fastcgi_param PATH_INFO $fastcgi_path_info;
}

fastcgi_pass app:9000 sends PHP requests to the app service by its Compose name.

Gzip Compression

nginx
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript;
gzip_vary on;
gzip_comp_level 6;
gzip_min_length 1000;
gzip_proxied any;

Gzip level 6 for text, JSON, JavaScript and XML responses, only above 1000 bytes.

PHP-FPM Configuration

The pool settings live in docker/php/www.conf.

Process Manager Settings

ini
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 10
pm.max_requests = 500

A dynamic process manager: up to 50 children, 5 to 10 spare, and each worker is recycled after 500 requests to contain memory leaks.

Timeouts and Logging

ini
pm.process_idle_timeout = 10s
request_terminate_timeout = 30s
request_slowlog_timeout = 5s
slowlog = /proc/self/fd/2
php_admin_value[error_log] = /proc/self/fd/2
php_admin_flag[log_errors] = on

Requests are killed after 30 seconds (request_terminate_timeout), anything slower than 5 seconds goes to the slow log, and errors go to the container log.

Security Settings

ini
php_admin_value[memory_limit] = 256M
php_admin_value[disable_functions] = "exec,passthru,shell_exec,system"

memory_limit is 256M, and exec, passthru, shell_exec and system are disabled.

Performance Optimizations

PHP-FPM Configuration

The pm.* values above are the tuning.

Supervisor Configuration for Queue Workers

ini
[supervisord]
nodaemon=true
logfile=/var/www/storage/logs/supervisord.log
pidfile=/var/run/supervisor/supervisord.pid
user=www-data
loglevel=info

[supervisorctl]
serverurl=unix:///var/run/supervisor/supervisor.sock

[unix_http_server]
file=/var/run/supervisor/supervisor.sock
chmod=0700
username=www-data
password=www-data

[program:php-fpm]
command=php-fpm -F
autostart=true
autorestart=true
priority=10
user=www-data
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0

[program:horizon]
process_name=%(program_name)s
command=php /var/www/artisan horizon
autostart=true
autorestart=true
user=www-data
redirect_stderr=true
stdout_logfile=/var/www/storage/logs/horizon.log
stopwaitsecs=3600
stopasgroup=true
killasgroup=true

[program:vite]
command=npm run dev
directory=/var/www
autostart=true
autorestart=true
user=www-data
redirect_stderr=true
stdout_logfile=/var/www/storage/logs/vite.log
environment=NODE_ENV=development

Nginx Optimization

Gzip and the one-year static asset cache from the Nginx section are the only tuning. FastCGI caching is deliberately absent: it needs a fastcgi_cache_path in the http block and a cache key, and caching dynamic Laravel responses is risky in development.

Using Makefile for Simplicity

The Makefile wraps the long docker compose exec app ... commands in short targets.

What is a Makefile?

make <target> runs the commands listed under that target.

Benefits of Using Make with Docker

Everyone on the team runs the same commands, and the Makefile doubles as their documentation.

Our Docker Makefile

makefile
.PHONY: up down build install migrate fresh test setup-test-db

# Start the application
up:
	docker compose up -d

# Stop the application
down:
	docker compose down

# Build containers
build:
	@echo "Setting up the project..."
	@if [ ! -f .env ]; then \
		cp .env.local .env; \
		echo "Created .env file from .env.local"; \
	fi
	docker compose build

# Install dependencies
install:
	docker compose exec app composer install
	docker compose exec app npm install

# Run migrations
migrate:
	docker compose exec app php artisan migrate

# Fresh migrations
fresh:
	docker compose exec app php artisan migrate:fresh

# Setup test database
setup-test-db:
	docker compose exec mysql sh -c 'mysql -uroot -p"$$MYSQL_ROOT_PASSWORD" -e "CREATE DATABASE IF NOT EXISTS laravel_test;"'
	docker compose exec app php artisan migrate --env=testing

# Run tests
test: setup-test-db
	docker compose exec app php artisan test --env=testing

# Run quality tools
quality:
	docker compose exec app composer larastan
	docker compose exec app composer pint
	docker compose exec app npm run format
	docker compose exec app npm run types
	docker compose exec app npm run lint

# Setup project from scratch
setup: build up
	docker compose exec app composer install
	docker compose exec app npm install
	docker compose exec app php artisan key:generate
	docker compose exec app php artisan migrate
	@echo "Project setup completed!"

# Show logs
logs:
	docker compose logs -f

# Enter app container
shell:
	docker compose exec app bash

# Clear all caches
clear:
	docker compose exec app php artisan cache:clear
	docker compose exec app php artisan config:clear
	docker compose exec app php artisan route:clear
	docker compose exec app php artisan view:clear

# Start Vite development server
vite:
	docker compose exec app npm run dev

Using the Makefile

Day-to-day use:

bash
# Set up the entire project with one command
make setup

# Start the development environment
make up

# Run database migrations
make migrate

# Access the app container shell
make shell

# Start the Vite development server
make vite

make setup builds the images, starts the containers, installs dependencies, generates the app key and migrates. That is all a new developer needs.

Development Tools

Testing URLs

  • Main application: http://localhost
  • MailHog interface: http://localhost:8025 (for email testing)
  • Queue monitoring: http://localhost/horizon (if Horizon is installed)

Workflow Example

A typical day:

  1. Clone the project and start containers:

    bash
    git clone https://github.com/your-username/your-project.git
    cd your-project
    make setup  # Builds containers, installs dependencies, runs migrations
    
  2. Edit code in your IDE: the project directory is mounted into the container, so changes apply immediately

  3. Run migrations after database changes:

    bash
    make migrate
    
  4. Start frontend asset compilation:

    bash
    make vite
    
  5. Test emails using MailHog:

    • Trigger an email in your application
    • View it at http://localhost:8025
  6. Run tests:

    bash
    make test
    
  7. Shut down when done:

    bash
    make down
    

Useful Commands

bash
# View logs in real-time
make logs

# Clear all Laravel caches
make clear

# Get a shell in the app container
make shell

# Completely rebuild the containers
make build

Troubleshooting

Common Issues and Solutions

1. Permission Denied Errors

Error: EACCES: permission denied, open '/var/www/storage/logs/laravel.log'

Solution: Fix permissions and update USER_ID/GROUP_ID in your .env file

bash
# Append your host IDs to .env (Compose does not run $(...) inside .env files)
echo "USER_ID=$(id -u)" >> .env
echo "GROUP_ID=$(id -g)" >> .env

# Then rebuild
make build

2. Port Already in Use

Error starting userland proxy: listen tcp4 0.0.0.0:80: bind: address already in use

Solution: Change the port in docker-compose.yml or stop the service using port 80

yaml
# In docker-compose.yml
ports:
  - "8080:80"  # Change 80 to 8080

3. MySQL Connection Issues

SQLSTATE[HY000] [2002] Connection refused

Solution: Check your .env file settings

DB_CONNECTION=mysql
DB_HOST=mysql  # Must match service name in docker-compose.yml
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=your_password

4. Missing Node Modules

If you're getting errors about missing Node modules:

Solution: Reinstall Node modules

bash
make install

5. Docker Containers Not Starting

If containers fail to start, check the logs:

Solution:

bash
docker compose logs

Best Practices

Three things this setup gets right: the app runs as www-data with its UID and GID matched to the host user (USER_ID/GROUP_ID), .env is mounted instead of baked into the image, and the MySQL and Redis healthchecks gate startup. Don't carry the file to production as is: it publishes the MySQL, Redis and PHP-FPM ports to the host and runs Vite inside the app container.

Conclusion

Five services, one Dockerfile for PHP and a Makefile so that make setup is the only command a new developer has to know. The next article covers optimizing Docker images for production, including Alpine-based images.

Source Code

The complete code is on GitHub.

Docker & Laravel Glossary

  • Container: A lightweight, standalone, executable software package
  • Image: A template used to create containers
  • Docker Compose: A tool for defining and running multi-container applications
  • Volume: Persistent storage that exists outside containers
  • Dockerfile: A script with instructions to build a Docker image
  • Laravel Horizon: A queue monitoring dashboard for Laravel Redis queues
  • MailHog: A development tool for email testing
  • PHP-FPM: PHP FastCGI Process Manager for handling PHP requests
  • Supervisor: A process control system to manage processes
  • Makefile: A file containing a set of directives used by the make build automation tool

Related articles

Existing system support

Need help with a live application?

I help companies improve live systems, clean up delivery workflows, and ship new features without adding avoidable complexity.

Comments (0)
Sign in to leave a comment

You need to be signed in to add a comment.

Login

Need someone to take responsibility for the next step?

Let’s talk about your project and define a scope that actually makes sense for your goals.