‹ All Docker Interview Questions questions

Docker Interview Question 9: Compose Depends on Healthy

Docker Interview Questions · Test 1 · question 9 of 10

Docker Composemedium

A compose.yaml defines web and a PostgreSQL service db, with depends_on: [db] under web. On docker compose up, db starts first, but web often crashes at startup with "connection refused" while PostgreSQL is still initializing. Restarting web a few seconds later always works. How should you fix the startup order in Compose?

Select one answer
Show answer and explanation

Answer:

  • D. Give db a healthcheck (for example with pg_isready) and set condition: service_healthy under web's depends_on entry for db

Plain depends_on controls only the start order: Compose waits until the dependency container is running, not until it is "ready". A database that is still initializing is running but cannot yet accept connections. With condition: service_healthy, Compose waits until the dependency reports healthy, as defined by its healthcheck, before it starts the dependent service.

Option A has no effect. Compose uses depends_on, not the order of services in the file, to decide startup order.

Option B is just the long form of the existing behaviour; service_started waits for the container to start, not for it to be ready.

Option C changes what happens when db exits. db is not failing here, and a restart policy on db does nothing to delay web.

Reference: Control startup and shutdown order in Compose

Practice Test 1 ›

Study guides for Docker Interview Questions