Menu

Docker Compose depends_on Doesn't Wait for the Database: Fix "Connection Refused" on Startup
📰

Docker Compose depends_on Doesn't Wait for the Database: Fix "Connection Refused" on Startup

DEV Community: docker·Libme·about 1 month ago
#6iN8tnBo
#devtodocker#devto#dev#compose#healthcheck
Long article (1378 words) — no AI summary yet.
Reading 0:00
15s threshold

Short answer: plain depends_on only waits until the dependency's container has started , not until the process inside is ready. To make the app wait for Postgres, give the database a healthcheck and use depends_on with condition: service_healthy . Then add a connection retry in the app anyway, because a healthcheck narrows the race but cannot close it.

What does the failure look like?

You run docker compose up on a fresh checkout. The database container starts, the API container starts a moment later, and the API dies:

api-1 | psycopg2.OperationalError: connection to server at "db" (172.19.0.2), port 5432 failed: Connection refused api-1 | Is the server running on that host and accepting TCP/IP connections? db-1 | PostgreSQL init process complete; ready for start up.

Enter fullscreen mode

Exit fullscreen mode

Run it again and it works, because the data volume now exists and Postgres boots in a second instead of ten. That "works on the second try" pattern is the signature of a startup race.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.