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.…