Docker Compose Builder · PHP / Laravel + MySQL

Docker Compose Laravel + MySQL 8 + Redis Queue Stack & Healthcheck Guide

Generate a Compose Specification docker-compose.yml and matching .env.example for PHP / Laravel + MySQL with native binary healthchecks, service_healthy boot ordering, and firewall-safe port bindings.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Runtime & Data Services

2. Healthchecks, Workers & Security

# docker-compose.yml — Modern Compose Specification (no obsolete 'version:' attribute)
# Generated by OpsCheck DevTools (Laravel PHP)
name: laravel_mysql_stack

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    restart: unless-stopped
    env_file:
      - .env
    ports:
      - "127.0.0.1:8000:8000"
    environment:
      DB_HOST: mysql
      DB_PORT: "3306"
      REDIS_HOST: redis
      REDIS_PORT: "6379"
    depends_on:
      mysql:
        condition: service_healthy
      redis:
        condition: service_healthy
    networks:
      - app_network

  worker:
    build:
      context: .
      dockerfile: Dockerfile
    command: php artisan queue:work --sleep=3 --tries=3 --max-time=3600
    restart: unless-stopped
    env_file:
      - .env
    environment:
      DB_HOST: mysql
      DB_PORT: "3306"
      REDIS_HOST: redis
    depends_on:
      mysql:
        condition: service_healthy
      redis:
        condition: service_healthy
    networks:
      - app_network

  mysql:
    image: mysql:8.0
    restart: unless-stopped
    environment:
      MYSQL_DATABASE: ${DB_DATABASE:-app_db}
      MYSQL_USER: ${DB_USERNAME:-app}
      MYSQL_PASSWORD: ${DB_PASSWORD:-change_me_strong}
      MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:-root_change_me}
    # Kept strictly internal on app_network (prevents Docker iptables UFW bypass)
    expose:
      - "3306"
    volumes:
      - db_data:/var/lib/mysql
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p$$MYSQL_ROOT_PASSWORD"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 20s
    networks:
      - app_network

  redis:
    image: redis:7-alpine
    command: redis-server --appendonly yes
    restart: unless-stopped
    expose:
      - "6379"
    volumes:
      - redis_data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 10s
    networks:
      - app_network

networks:
  app_network:
    driver: bridge

volumes:
  db_data:
  redis_data:
Service Boot Orderbridge: app_network
mysql(healthy)+redis(healthy)appworker

Healthcheck & Security Diagnostics

Compose Spec v2+
  • passStartup Race Condition Prevented (condition: service_healthy)

    app and worker will wait until mysql and redis pass their native healthchecks before starting.

  • infoInternal Bridge DNS Hostnames (Never Use localhost Inside Containers)

    Connect over the shared app_network using Docker service names: DB_HOST=mysql (port 3306), REDIS_HOST=redis (port 6379). Inside the "app" container, 127.0.0.1/localhost points only to "app" itself and always refuses DB/broker connections.

  • passFirewall-Safe Port Exposure Enabled (127.0.0.1 / Internal expose:)

    Database and broker ports stay strictly isolated on app_network via expose:, and app ports bind to 127.0.0.1 so Docker never bypasses host UFW/nftables rules.

  • passNative Probe Binaries Used (mysqladmin ping & redis-cli ping)

    Generated healthchecks invoke built-in service binaries rather than curl or wget, avoiding false "unhealthy" states in minimal Alpine and slim official images.

  • passPersistent Named Volumes Declared (db_data, redis_data)

    Top-level named volumes preserve database tables and broker queues across container rebuilds and "docker compose down" (data is only removed if you pass -v).

Runs locally in your browser. Compose YAML and environment templates are generated client-side.

Typical Container Boot & Connection Error (PHP / Laravel + MySQL)

When depends_on lacks condition: service_healthy or internal service hostnames are misconfigured in .env, container logs typically surface this error during startup:

docker compose logs (Startup Failure)

SQLSTATE[HY000] [2002] Connection refused (Connection: mysql, SQL: select * from `sessions` where `id` = ... limit 1)

Container Boot Ordering, Bridge DNS & Persistence for PHP / Laravel + MySQL

Containerizing a Laravel 11 or Laravel 12 application alongside MySQL 8, Redis 7, and a dedicated php artisan queue:work container eliminates environment drift across developer laptops and production servers; but only when startup order and internal container networking are configured accurately. A fresh MySQL 8 container takes 10 to 25 seconds to initialize its InnoDB tablespace, root credentials, and system schemas before opening TCP port 3306.

If your docker-compose.yml uses a simple list-style depends_on: [mysql, redis], Docker launches your Laravel web container and queue worker milliseconds after the MySQL process spawns. Any entrypoint running php artisan migrate --force or php artisan queue:work immediately crashes with SQLSTATE[HY000] [2002] Connection refused and enters an endless restart loop until MySQL finishes bootstrapping.

By attaching native binary healthchecks (mysqladmin ping for MySQL 8 and redis-cli ping for Redis 7) and wiring depends_on with condition: service_healthy, Docker Compose pauses both the Laravel app container and the queue worker until both data stores actively respond to protocol-level probes. Because both binaries ship inside the official images, healthchecks never fail due to missing curl or wget utilities.

On the networking side, Laravel's .env inside Docker must reference service DNS names (DB_HOST=mysql and REDIS_HOST=redis) rather than 127.0.0.1, which points back to the PHP container itself. Keeping MySQL and Redis isolated on a user-defined bridge network via expose: (instead of publishing 3306:3306 to 0.0.0.0) also prevents Docker's iptables rules from exposing your database to the public internet on UFW-protected VPS hosts.

Finally, declaring top-level named volumes (db_data and redis_data) guarantees that running docker compose down during a PHP upgrade preserves all MySQL tables and queued Redis jobs cleanly. Combined with separate app and worker containers sharing the same built image, you can scale queue throughput independently without duplicating Dockerfile build logic.

Before rolling out a Laravel, MySQL 8, and Redis Compose stack to production, run docker compose config to verify that every $${MYSQL_ROOT_PASSWORD} escape and .env secret resolves cleanly without leaking blank passwords. Checking docker compose ps right after a cold boot confirms both mysql and redis transition cleanly from (health: starting) to (healthy) before Laravel and queue:work begin processing HTTP requests and background jobs.

Step-by-Step PHP / Laravel + MySQL Docker Compose Setup Guide

Follow each step below to pair the generated Compose file with accurate container DNS variables, safe database migrations, and zero-downtime restarts.

  1. 1Point Laravel .env to Docker Service DNS Names

    .env

    Inside the shared Docker bridge network, set DB_HOST=mysql and REDIS_HOST=redis so both the web container and queue worker resolve sibling containers via Docker's embedded DNS server.

    .envdotenv
    APP_ENV=production
    APP_URL=https://api.example.com
    
    DB_CONNECTION=mysql
    DB_HOST=mysql
    DB_PORT=3306
    DB_DATABASE=app_db
    DB_USERNAME=app
    DB_PASSWORD=change_me_strong
    DB_ROOT_PASSWORD=root_change_me
    
    CACHE_STORE=redis
    QUEUE_CONNECTION=redis
    SESSION_DRIVER=redis
    REDIS_HOST=redis
    REDIS_PORT=6379
  2. 2Run Database Migrations Safely After Healthchecks Pass

    terminal

    Wait for docker compose up -d to confirm mysql (healthy) and redis (healthy), then execute production migrations inside the running app container without risking concurrent migration races across replicas.

    terminalbash
    docker compose up -d --build
    docker compose ps
    docker compose exec app php artisan migrate --force
    docker compose exec app php artisan optimize
  3. 3Configure Graceful Queue Worker Shutdowns

    docker/queue-check.sh

    Pass --max-time=3600 and --tries=3 to php artisan queue:work so workers recycle memory periodically and finish in-flight jobs cleanly when Docker sends SIGTERM during deployments.

    docker/queue-check.shbash
    # Restart workers gracefully after deploying updated PHP code:
    docker compose exec app php artisan queue:restart
    docker compose logs -f worker
  4. 4Verify MySQL 8 Authentication Plugin and Volume Persistence

    terminal

    Confirm PHP PDO connects cleanly using MySQL 8's default caching_sha2_password plugin (supported natively in PHP 8.2+) and verify the named db_data volume is attached.

    terminalbash
    docker compose exec app php artisan db:show
    docker volume ls | grep db_data

Common PHP / Laravel + MySQL Docker Compose Pitfalls

Avoid these three container orchestration mistakes before deploying your Compose stack onto staging or production servers.

Pitfall 1

MySQL 8 Temporary Initialization Server Causing Premature Health Pass

On a brand-new empty volume, MySQL 8 starts a temporary init server, shuts it down, and restarts for real traffic. Setting start_period: 20s and interval: 10s with retries: 5 prevents false-negative health failures during first boot.

Pitfall 2

Running docker compose down -v and Wiping Production MySQL Data

Appending the -v flag to docker compose down permanently deletes named volumes like db_data and redis_data. Always use plain docker compose down during maintenance and automate mysqldump backups off-host.

Pitfall 3

Publishing "3306:3306" on a Cloud VPS Protected Only by UFW

Docker writes DNAT rules directly into iptables PREROUTING before UFW chains execute. Publishing 3306:3306 exposes MySQL to 0.0.0.0 globally; always use expose: ["3306"] or bind to 127.0.0.1:3306:3306.

Related Tools

Pair Your Docker Compose Stack With .env Linting, Nginx TLS & CORS Checks

Validate your .env file for unescaped $$ interpolation or leaked secrets, configure Nginx DNS resolution, and verify cross-origin headers:

Frequently Asked Questions

Why does Laravel throw SQLSTATE[HY000] [2002] Connection refused when MySQL is running?
Two causes account for 95% of cases: either DB_HOST is still set to 127.0.0.1 instead of the Docker Compose service name "mysql", or Laravel booted before MySQL finished initializing because depends_on lacked condition: service_healthy.
Why does mysqladmin ping need $$MYSQL_ROOT_PASSWORD with double dollar signs?
Docker Compose interpolates single $VAR variables from the host .env before passing YAML to Docker. Writing $$MYSQL_ROOT_PASSWORD escapes the dollar sign so the MySQL container evaluates its own runtime environment variable inside the healthcheck shell.
Should Laravel queue:work run in the same container as PHP-FPM/Octane or its own service?
Running queue:work in its own Compose service (sharing the exact same built Docker image) follows Docker's one-process-per-container best practice, keeps container stdout logs separate, and lets Docker restart crashed workers automatically.
Do I still need a version: "3.9" line at the top of docker-compose.yml?
No. Docker Compose v2 deprecated the top-level version: field and prints a warning whenever it is present. Modern Compose Specification files omit version: and optionally declare name: instead.
Browse all 10 Compose stacks →