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:
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.
1Point Laravel .env to Docker Service DNS Names
.envInside 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.
.envdotenvAPP_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=63792Run Database Migrations Safely After Healthchecks Pass
terminalWait 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.
terminalbashdocker compose up -d --build docker compose ps docker compose exec app php artisan migrate --force docker compose exec app php artisan optimize3Configure Graceful Queue Worker Shutdowns
docker/queue-check.shPass --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 worker4Verify MySQL 8 Authentication Plugin and Volume Persistence
terminalConfirm 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.
terminalbashdocker 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.
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.
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.
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.
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:
Validate Laravel 11/12 .env files locally in your browser. Fix InvalidFileException, unquoted # in DB_PASSWORD, invalid base64 APP_KEY, and config:cache traps.
Serve a built React Vite dist/ SPA at / with try_files history fallback while proxying /api/ to your backend on the same Nginx domain to eliminate CORS.
Simulate and fix CORS preflight errors between Laravel 11/12 APIs and React Vite on port 5173. Generate config/cors.php with credentials and header rules.
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.
Related Docker Compose Stack Guides
Browse all 10 Compose stacks →Docker Compose Laravel Octane + PostgreSQL 16 + Reverb WebSockets Guide
Generate a Docker Compose stack for Laravel Octane, PostgreSQL 16, Redis 7, and Laravel Reverb WebSockets with pg_isready healthchecks and firewall safety.
Docker Compose Laravel + PostgreSQL 16 + Meilisearch + Redis Stack Guide
Generate a full-stack Docker Compose setup for Laravel Scout with PostgreSQL 16, Redis 7, and Meilisearch using native healthchecks and persistent volumes.
Docker Compose FastAPI + PostgreSQL 16 + Celery Worker Healthcheck Guide
Build a production Docker Compose stack for Python FastAPI, PostgreSQL 16, Redis 7, and Celery workers with pg_isready healthchecks and Alembic migrations.
Docker Compose WordPress + MariaDB 11 + Redis + Nginx Healthcheck Guide
Build a fast Docker Compose stack for WordPress, MariaDB 11, Redis 7 object cache, and Nginx using built-in healthcheck.sh and redis-cli ping probes.