If you only want a one-line answer: the SQLSTATE[HY000] [2002] Connection refused error in a Laravel app running inside Docker almost always has one of three causes - (1) DB_HOST=127.0.0.1 or localhost in .env instead of the MySQL service name in compose, (2) using the host-mapped port instead of the in-network Docker port, or (3) the app starting before MySQL is ready because the database service lacks a healthcheck. This guide breaks down exactly these three scenarios so whenever you hit Laravel Docker MySQL connection refused, you reach a fix in under ten minutes. The rest of the article unpacks all three with a runnable compose.yaml, real in-container commands, and a final checklist. If you see exactly that error message - SQLSTATE[HY000] [2002] docker compose - in your app logs, the next sections are for you.
Prerequisites: What You Should Know Before Reading
This article is for someone who:
- Works with Laravel 10+ and knows the Service Container, ENV, and
php artisanconcepts. - Has at least once run a multi-service stack with
docker compose up. - Has seen this message: "SQLSTATE[HY000] [2002]: Connection refused" in the app logs, while MySQL was running in another container.
If you are new to Docker, first skim the official Compose services documentation and Laravel's Database guide, then come back. This article is written so that if you searched for "laravel docker database connection" or "fixing MySQL error in Laravel Docker", you get everything with real commands and code, not theory.
Real Demo: A Runnable compose.yaml with app + mysql + phpmyadmin
Most Stack Overflow answers show a half-baked docker-compose.yml that only works for one scenario. Here we build a complete, runnable compose.yaml where you can deliberately produce each of the three errors. Folder structure:
.
├── compose.yaml
├── .env
└── app/
└── (your Laravel project)
The .env File (Correct Version)
APP_NAME=LaravelDockerDemo
APP_ENV=local
APP_KEY=base64:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX=
APP_DEBUG=true
APP_URL=http://localhost:8080
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=laravel
DB_PASSWORD=secret
Key point: DB_HOST=mysql, not 127.0.0.1 and not localhost. The reason is in the next section.
The compose.yaml File (Correct Version - Copy and Run)
services:
app:
build:
context: ./app
dockerfile: Dockerfile
image: php:8.3-fpm
container_name: laravel-app
working_dir: /var/www/html
volumes:
- ./app:/var/www/html
environment:
DB_HOST: mysql
DB_PORT: 3306
DB_DATABASE: laravel
DB_USERNAME: laravel
DB_PASSWORD: secret
depends_on:
mysql:
condition: service_healthy
networks:
- laravel-net
ports:
- "8080:80"
mysql:
image: mysql:8.0
container_name: laravel-mysql
restart: unless-stopped
environment:
MYSQL_ROOT_PASSWORD: rootsecret
MYSQL_DATABASE: laravel
MYSQL_USER: laravel
MYSQL_PASSWORD: secret
volumes:
- mysql-data:/var/lib/mysql
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uroot", "-prootsecret"]
interval: 5s
timeout: 5s
retries: 20
start_period: 30s
networks:
- laravel-net
phpmyadmin:
image: phpmyadmin:latest
container_name: laravel-phpmyadmin
restart: unless-stopped
environment:
PMA_HOST: mysql
PMA_PORT: 3306
PMA_ARBITRARY: 1
ports:
- "8081:80"
depends_on:
mysql:
condition: service_healthy
networks:
- laravel-net
volumes:
mysql-data:
networks:
laravel-net:
driver: bridge
If you copy this file as-is and run docker compose up -d, the Laravel app comes up at http://localhost:8080 and phpMyAdmin at http://localhost:8081, with the MySQL connection working without errors. The next three sections show what small changes trigger each of the three common errors.
Error 1: DB_HOST=127.0.0.1 - The Classic In-Container localhost Mistake
Why Does It Happen?
When you run a Laravel app normally on your laptop, .env looks like:
DB_HOST=127.0.0.1
DB_PORT=3306
And it works, because MySQL is running on the same machine. When you bring this same .env into Docker without changes, the app connects to 127.0.0.1 inside the app container - not on your host. This is the classic laravel docker 127.0.0.1 localhost scenario that comes up again and again in Docker and Laracasts forums. Inside the app container nothing is listening on port 3306, so you get Connection refused.
How to Reproduce It Deliberately
Just change DB_HOST in .env back to 127.0.0.1:
DB_HOST=127.0.0.1
DB_PORT=3306
Then docker compose up -d and inside the app container:
docker compose exec app php artisan migrate
Actual Output:
SQLSTATE[HY000] [2002] Connection refused
at vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70
Diagnosis With an In-Container Command:
docker compose exec app bash -lc 'ss -ltnp | grep 3306 || echo "no mysql port inside app"'
If the output is no mysql port inside app, the app is looking for MySQL on itself - that is the signature of error 1.
Fix:
DB_HOST=mysql # Service name in compose.yaml - the correct DB_HOST mysql laravel combo
DB_PORT=3306
After every .env change, clear the config cache inside the app container (covered in its own section). One more thing about php artisan config clear docker here: run php artisan config:clear inside the app container, not on the host. Because bootstrap/cache/config.php is mounted into the app, not onto your host:
docker compose exec app php artisan config:clear
Error 2: Wrong Port - Why the In-Network Docker Port Doesn't Matter
Why Does It Happen?
Some people set DB_PORT to the host port (for example 3307 as defined in ports: "3307:3306"). But that port is for connecting from outside the container to inside, not for container-to-container. Inside the internal Docker network (laravel-net in our example), each service listens on its software's real port. MySQL is always on 3306.
The definitive answer, quoting the official Docker forum:
When using a shared compose file, you can access your DB from any of those containers within the same Docker network using
database:3306(service name and default port). The ports mapping is not relevant when inside a Docker network, it maps the ports to the outside world.
How to Reproduce It Deliberately
DB_HOST=mysql
DB_PORT=3307 # Wrong - this port only makes sense from the host
Then docker compose exec app php artisan tinker and in tinker:
DB::connection()->getPdo();
Actual Output:
SQLSTATE[HY000] [2002] Connection refused
Diagnosis With an In-Container Command:
docker compose exec app bash -lc 'getent hosts mysql'
# laravel-mysql 172.20.0.3 ← name resolution is correct
docker compose exec app bash -lc 'timeout 3 bash -c "</dev/tcp/mysql/3306" && echo OK || echo "refused on 3306"'
If you get refused on 3306, MySQL is not listening on port 3306 inside the network (or it has not come up at all). To confirm where MySQL is listening:
docker compose exec mysql bash -lc 'ss -ltnp | grep 3306'
# tcp LISTEN 0 151 0.0.0.0:3306 0.0.0.0:* users:(("mysqld",...))
Fix:
DB_PORT=3306 # The internal MySQL port, not the host port
Error 3: DB Is Not Ready Yet - docker compose mysql healthcheck
Why Does It Happen?
This error is very sneaky. You correctly set DB_HOST=mysql and DB_PORT=3306, MySQL is running in the mysql container, but on the first request after docker compose up the app throws Connection refused. The reason: the MySQL container is started from Docker's perspective, but the MySQL daemon itself is still initializing (especially with an empty volume on first creation, it can take 10 to 30 seconds).
According to the official Compose documentation on depends_on, the short syntax only waits for service_started, not service_healthy. If you want the app to actually wait for MySQL to be ready, you need the long syntax with depends_on condition service_healthy:
depends_on:
mysql:
condition: service_healthy
And the mysql service itself must have a healthcheck (which is in the compose.yaml above). The mysqladmin ping healthcheck pattern is the cheapest way to detect "MySQL is actually ready to accept connections":
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uroot", "-prootsecret"]
interval: 5s
timeout: 5s
retries: 20
start_period: 30s
How to Reproduce It Deliberately
Write depends_on in the short form in compose.yaml:
depends_on:
- mysql
And remove the healthcheck from the mysql service. With these settings, the app starts before MySQL is ready and the first 20-30 seconds of requests fail.
Diagnosis With an In-Container Command:
docker compose ps
# Check the STATUS column for each service
docker compose logs mysql --tail=50
docker compose exec mysql mysqladmin ping -h localhost -uroot -prootsecret
# mysqld is alive
If the STATUS of the app service is Up but the STATUS of the mysql service is still health: starting, the app started too early. That is the signature of error 3.
Fix:
Switch depends_on back to the long syntax with condition: service_healthy, and add the standard MySQL healthcheck. Both are in the sample compose.yaml from the start of this article.
Differential Diagnosis: One Table, Three Errors
This table is something you will not find in any Stack Overflow answer or Laracasts video. Each error has a quick in-container command to identify it:
| Error | Log Signature | Diagnostic Command (on host) | Success Result | Failure Result (= This Error) |
|---|---|---|---|---|
| Error 1: DB_HOST=127.0.0.1 | SQLSTATE[HY000] [2002] |
docker compose exec app bash -lc 'ss -ltnp | grep 3306' |
LISTEN ... 3306 (if mysqld is there too) |
no mysql port inside app |
| Error 2: Wrong port | SQLSTATE[HY000] [2002] |
docker compose exec mysql ss -ltnp | grep 3306 |
0.0.0.0:3306 |
Empty (or another port) |
| Error 3: DB not ready | SQLSTATE[HY000] [2002] + app up but DB not |
docker compose ps |
Both Up (healthy) |
Up and health: starting |
Error 4 (hidden): Cached .env |
Error persists even after fix | docker compose exec app ls -la bootstrap/cache/ |
config.php absent |
config.php exists and is stale |
Anti-Pattern: config:cache + Docker
A class of bug I have seen in captaincode projects and several client projects: changing DB_HOST in .env has no effect because bootstrap/cache/config.php was built earlier. Inside Docker this is even worse because the container usually boots once with the initial env, and if the config cache was created during build or in the entrypoint, it stays that way for the container's whole life.
If your logs keep showing [2002] even after you change DB_HOST in .env and docker compose restart app, run this inside the app container first:
docker compose exec app php artisan config:clear
docker compose exec app rm -f bootstrap/cache/config.php
docker compose restart app
The full explanation of this trap is in the separate article about config:cache and env changes, but if you are in the middle of this error right now, those three lines resolve this class of failure in most cases.
Final Checklist Before docker compose up
Review this list every time before bringing up a Laravel + MySQL stack. Each item is one line or one config line:
-
DB_HOSTin.envequals the service name incompose.yaml(for examplemysql), not127.0.0.1orlocalhost. -
DB_PORT=3306(MySQL's internal port), not the port you mapped to the host inports:. -
DB_DATABASEandDB_USERNAMEmatch theMYSQL_DATABASEandMYSQL_USERvalues in themysqlservice. - The
mysqlservice has ahealthcheckwithmysqladmin ping. -
depends_onin theappservice is written in long syntax withcondition: service_healthy. - After every
.envchange, you ranphp artisan config:clearinside the app container. - If you have run
docker compose upbefore:docker compose down -vand thenupagain (to wipe the volume if you need a reset). - You checked the MySQL logs with
docker compose logs mysql --tail=50and saw the phraseready for connections. - You checked the app logs with
docker compose logs app --tail=50and did not see the[2002]error after start.
What to Read Next
If the [2002] error is gone but a different one appeared, these three articles continue the same path:
Access denied for userorUnknown database: usuallyDB_DATABASE/DB_USERNAMEdo not matchMYSQL_DATABASE/MYSQL_USER. Before touching the database, see debugging the Laravel queue with Supervisor, which covers the same env-and-restart logic.- If services come up but you get
502 Bad Gateway, MySQL is not the problem; fixing 502 in Nginx and PHP-FPM shows the right path. - If jobs are not running, troubleshooting cron and the Scheduler covers the three layers you need.
For real projects where you do not want to spend time on infrastructure config, Captain Code services handle setup and optimization of exactly this stack, and if you want small fast tools, the labs has ready-made ones.
Frequently Asked Questions
Should I set DB_HOST=localhost or 127.0.0.1?
Neither. Inside Docker, localhost and 127.0.0.1 both point to the app container itself, not to the MySQL container. You must use the service name from compose.yaml (for example mysql). Docker's internal DNS resolves that name to the MySQL container's IP within the bridge network.
Why does docker compose up come up without errors but the first request fails?
Because MySQL is initializing and has not yet opened port 3306, but the app container is already started from Docker's point of view. If depends_on is short or the healthcheck is missing, the app starts too early. Fix: healthcheck with mysqladmin ping + depends_on with condition: service_healthy.
What is the difference between service_started and service_healthy in depends_on?
service_started means the container has started running (but the software inside may not be ready yet). service_healthy means the service's healthcheck returned healthy. For databases you always need service_healthy. This feature is available from Docker Compose 2.17.0 onwards.
What does mysqladmin ping do and why is it used in the healthcheck?
mysqladmin ping is a command-line client that connects to the MySQL daemon and, if the daemon responds, returns exit code 0. It is the cheapest way to detect "MySQL is actually ready to accept connections" because it only performs a short TCP handshake.
The error persists even after changing .env; why?
Three possibilities: (1) bootstrap/cache/config.php is still holding the old values - run php artisan config:clear. (2) The app container booted with the initial env and does not re-read it - you need docker compose restart app. (3) You changed docker-compose.yml but did not run docker compose up -d again, or the env was not re-injected at the container level.
If you fix one of these three errors but get a new one (for example Access denied for user or Unknown database 'laravel'), those are separate stories I will cover in a future article. For now, if you start with the sample compose.yaml above and follow the checklist, most SQLSTATE[HY000] [2002] problems in Laravel + Docker trace back to one of these three causes.