tezvyn:

Docker Compose: Control Startup with `depends_on`

AI-drafted, machine-checkedSource: docs.docker.comintermediate

`depends_on` controls service startup order in Docker Compose, ensuring a database starts before your app. The footgun: it only waits for the container to start, not for the application inside to be ready. Use `healthcheck` for true readiness.

WHY IT EXISTS: In a multi-container application, services often have dependencies. A web server needs its database; a backend needs its cache. Without an explicit order, services start unpredictably, leading to connection errors and startup failures. depends_on was created to enforce a simple, predictable startup sequence.

THE MENTAL MODEL: Think of depends_on as telling Docker Compose, "Don't start this service until its required friends are running." It establishes a clear chain of command for starting your containers, preventing race conditions where an application tries to connect to a service that hasn't even been created yet.

HOW IT WORKS: When you run docker compose up, Compose analyzes the depends_on configuration to build a dependency graph. It starts services with no dependencies first. Then, it starts the services that depend on them, and so on, moving up the graph. For shutdown with docker compose down, the order is reversed: services are stopped first, then their dependencies.

WHEN TO USE IT: Use depends_on whenever one service has a hard requirement on another service being started first. The most common case is an application service depending on a database, cache, or a message queue. It's a fundamental tool for orchestrating any non-trivial Compose application.

WHEN NOT TO USE IT: The biggest footgun is relying on depends_on to guarantee a service is ready. It only waits for the container to start, not for the process inside (like a database initializing) to be ready for connections. If you need to wait for true readiness, use the expanded syntax with a condition: service_healthy and define a healthcheck in the dependency service. For complex cases, you might need a wrapper script or application-level connection retries.

ONE CANONICAL EXAMPLE: A web service that must wait for a postgres database to be healthy before starting. The web service's depends_on block specifies a condition: service_healthy for the db service. The db service in turn has a healthcheck that uses pg_isready to confirm the database process is accepting connections. The web container will not start until pg_isready succeeds.

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.