How can I make Docker Compose wait for MySQL to be ready before starting my app?

0
4
Asked By MellowCedar47 On

I'm following a Docker Compose getting-started workshop, but the example in the Compose section fails on the first startup. The app starts connecting to MySQL before the database has finished initializing, resulting in `ECONNREFUSED` on port 3306. If I run `docker compose down` and then bring everything back up, it works because MySQL has already created and initialized its data.

Is this expected behavior, or is something wrong with my setup? What's the recommended way to write a Compose file so the application waits until MySQL is actually ready to accept connections, rather than merely waiting for the database container to start?

3 Answers

Answered By CopperMango8 On

This is a startup-readiness race, not necessarily a mistake in your setup. `depends_on` can control the order containers are started, but the MySQL process may still be initializing when the app tries to connect.

Add a health check to the database and make the app depend on the database becoming healthy:

```yaml
services:
mysql:
image: mysql:8
environment:
MYSQL_ROOT_PASSWORD: secret
MYSQL_DATABASE: app
healthcheck:
test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -uroot -p$$MYSQL_ROOT_PASSWORD --silent"]
interval: 5s
timeout: 3s
retries: 20
start_period: 20s

app:
build: .
depends_on:
mysql:
condition: service_healthy
restart: on-failure
```

Also make sure the app connects to `mysql:3306`, using the Compose service name, rather than `localhost` or a changing container IP. The health check handles initial startup, while the app should still retry connections if MySQL later restarts or becomes temporarily unavailable.

Answered By SilverPine6 On

For troubleshooting, sharing the complete Compose file is useful because connection settings, service names, and environment variables can also cause this error. But based on the logs and the fact that a second startup works, the database initialization race is the most likely explanation.

Answered By QuietOrbit22 On

The workshop's repository version includes a MySQL health check and a `service_healthy` dependency, although the written instructions apparently don't explain that part. You can inspect the database with `docker compose ps`, `docker compose logs mysql`, and `docker inspect` to confirm whether its health check is passing.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.