Manage startup order and readiness in Compose
dependency vs readiness distinction.
depends_on only orders start, not readiness; add a healthcheck to the DB and use depends_on with condition: service_healthy so the web app waits until the DB passes its health check.
WHAT THIS TESTS It checks the classic misconception that depends_on waits for readiness, and whether you know the health-check-driven fix plus the defensive app-side practice.
A GOOD ANSWER COVERS The core distinction: depends_on in its short form only orders container startup, it does not wait for the dependency's process to be ready to serve. So the web app can start while Postgres is still initializing and crash on a refused connection. The Compose fix is two-part: add a healthcheck to the database service, for example a test running pg_isready, with interval, timeout, and retries; then on the web service use the long-form depends_on with db: condition: service_healthy. Compose will hold the web app until the DB health check reports healthy. Even so, best practice is to make the app resilient with connection retries and backoff, since dependencies can also fail mid-run.
COMMON WRONG ANSWERS Believing depends_on alone waits for readiness. Adding sleep hacks in the entrypoint. Omitting the healthcheck so condition: service_healthy can never be satisfied. Relying solely on Compose ordering and skipping application-level retries.
LIKELY FOLLOW-UPS What exactly does a healthcheck define, and what are its parameters? Why is application-level retry still needed? How does this differ in Kubernetes with readiness probes?
ONE CONCRETE EXAMPLE The db service gets healthcheck: test: ["CMD-SHELL", "pg_isready -U app"] with retries. The web service declares depends_on: db: condition: service_healthy. On compose up, the web container does not launch until pg_isready succeeds, eliminating the startup race, and the app additionally retries the connection a few times as a safety net.
Read the original → docs.docker.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.