Does depends_on in Docker Compose wait until the database is ready?
By default no. depends_on only controls start order, not readiness. To wait for a healthy service, add a healthcheck and use depends_on with condition: service_healthy.
Explain it simply
Booking a taxi and the driver 'starting his car' are not the same as him reaching your gate. depends_on only guarantees the db container has been started before the api container, not that Postgres has finished initialising and accepts connections.
That gap causes the classic 'connection refused' crash on first boot. The fix is to give the database a healthcheck (for Postgres, pg_isready) and tell the api to wait for condition: service_healthy. Compose then holds the api back until the check passes. Other conditions are service_started (the default) and service_completed_successfully, useful for one-off migration jobs.
You should still make the app retry its database connection; databases can restart later, and no start-up ordering protects against that.
Example
services:
db:
image: postgres:16
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
retries: 5
api:
build: .
depends_on:
db:
condition: service_healthyWhat to say in the interview
"depends_on only orders container start, not readiness. I add a healthcheck to the database and use condition: service_healthy so the app waits, and I still add connection retries in the app."
Common mistakes
- Assuming depends_on means the database is accepting connections.