What does depends_on actually wait for in Docker Compose?
When you list services under depends_on in the short form, as a plain array of names, Compose controls start order and nothing else. It creates and starts the db container before the api container, and it stops them in reverse order on shutdown. Running docker compose up api also brings up its dependencies. What Compose does not do is look inside the dependency. As soon as the container's main process has been launched, the condition counts as met and the next service starts.
The gap between "the container is running" and "the service accepts connections" is where the trouble starts. A database container can take anywhere from a fraction of a second to many seconds to become usable. In that time it allocates memory, replays its write-ahead log, or, on a first run with an empty volume, initializes a data directory and executes init scripts. Your API container starts during that window, opens a connection pool, gets connection refused or an authentication error against a half-initialized database, and exits. If it has a restart policy, it may loop a few times and eventually succeed, which hides the bug instead of fixing it.
This race tends to show up in the same places:
- CI runners, which start from cold volumes and images and run on shared, slower CPUs.
- Fresh clones, where a teammate's first
uptriggers database initialization. - Migration jobs, which exit non-zero when they reach the database too early.
- Caches and brokers such as Redis or a message queue, which open their port slightly after the process starts.
A stack that works on a warm laptop and fails intermittently in a pipeline usually has this cause.
services:
db:
image: postgres:16
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: example-password # placeholder, not a real secret
POSTGRES_DB: appdb
volumes:
- db-data:/var/lib/postgresql/data # empty on first run, so init takes longer
migrate:
image: example/api:latest
command: ["./migrate", "up"]
environment:
DATABASE_URL: postgres://app:example-password@db:5432/appdb
# Starts as soon as the db container is running, which may be before
# Postgres accepts connections. On a cold CI runner this can exit non-zero.
depends_on:
- db
api:
image: example/api:latest
environment:
DATABASE_URL: postgres://app:example-password@db:5432/appdb
ports:
- "8080:8080"
# Waits only for the db and migrate containers to start. It does not wait
# for migrations to finish or for the database to be ready.
depends_on:
- db
- migrate
# Restarting can hide the race. The api loops until the db happens to be up.
restart: on-failure
volumes:
db-data:
A typical stack that uses short-form depends_on: Compose starts db, migrate and api in order, but migrate and api can still connect before Postgres is ready, which causes intermittent failures on cold starts.
How do service_started, service_healthy and service_completed_successfully differ?
The fix starts with the long-form syntax. The short form of depends_on is a list of service names. The long form is a map: each dependency name becomes a key, and under it you set a condition that states what "ready" means for that service. Compose blocks the dependent container until that condition holds.
| Condition | Compose waits until | Use it for |
|---|---|---|
service_started |
The dependency's container has been started | Sidecars, mock servers, anything without a meaningful readiness signal |
service_healthy |
The dependency's healthcheck reports healthy | Databases, caches, brokers with a real probe |
service_completed_successfully |
The dependency has exited with code 0 | One-shot migration, seed or schema-setup containers |
service_started is what the short form already does. Spell it out only when other dependencies in the same block use richer conditions, or when there is nothing better to wait for.
service_healthy depends entirely on the healthcheck defined on the dependency. Without one, the condition can never be met and Compose rejects the configuration. The condition is only as good as the probe behind it, which a later section covers.
service_completed_successfully treats a dependency as a task, not a long-running service. If the migration container exits non-zero, the dependent service does not start. You get a clear failure at the migration step instead of an API returning errors against a half-migrated schema.
For local and CI stacks, make service_healthy the default for every stateful dependency. It turns intermittent pipeline failures caused by timing into a deterministic wait.
services:
db:
image: postgres:16
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: example-password # placeholder, not a real secret
POSTGRES_DB: app
healthcheck:
# Real readiness probe: succeeds only once Postgres accepts connections
test: ["CMD-SHELL", "pg_isready -U app -d app"]
interval: 5s
timeout: 3s
retries: 10
migrate:
image: example/app:latest
command: ["./migrate", "up"] # one-shot task; exits 0 on success
depends_on:
db:
condition: service_healthy # don't migrate until the DB is reachable
mock-mail:
image: example/mock-smtp:latest # no meaningful readiness signal
api:
image: example/app:latest
depends_on:
db:
condition: service_healthy # stateful dependency: wait for the probe
migrate:
condition: service_completed_successfully # schema must be applied (exit code 0)
mock-mail:
condition: service_started # starting the container is enough
A Compose file using the long-form depends_on syntax so that the API waits for a healthy Postgres, a migration container that exited with code 0, and a started mock mail server.
How does Compose enforce these conditions?
Two components share the work: the Docker Engine runs the healthcheck, and Compose reads the result.
The engine owns health status. When a container has a healthcheck, the Docker daemon runs the test command inside that container on the configured interval. It treats exit code 0 as a pass and any non-zero exit, or a run longer than timeout, as a failure. It keeps a health status on the container: starting while no probe has passed yet, healthy after a pass, and unhealthy once consecutive failures reach retries. It also stores a short log of recent probe results. This happens whether or not any service depends on the container. Compose does not run the probe itself.
Compose owns ordering. On up, Compose builds a dependency graph from every service's depends_on entries and rejects cycles. It then walks the graph so that a service is created only after its dependencies have been handled. For each dependency edge it checks the declared condition against the container state the engine reports:
service_started: the dependency container is running.service_healthy: the engine reports the dependency's health status ashealthy. If it reportsunhealthy, Compose stops waiting and reports the dependency as failed.service_completed_successfully: the dependency container has exited and its exit code is 0. A non-zero exit fails the condition.
Services with no dependency path between them can start in parallel. Only the edges you declare add waiting.
The gate applies at startup only. Once a dependent service is started, Compose stops evaluating the condition for that up run. If the dependency later turns unhealthy, the engine updates its status, but Compose does not stop or restart the dependents. The last section of this article returns to that limitation.
How do you write a healthcheck that tests readiness, not just liveness?
A healthcheck runs inside the container, so it can only call binaries that exist in that image. Database images usually include a client that speaks the real protocol, and those clients make the best probes. pg_isready reports whether Postgres is accepting connections. mysqladmin ping asks the MySQL server directly. redis-cli ping expects PONG. Prefer the exec form (CMD) over CMD-SHELL. Exec form avoids an extra shell process and quoting problems, and it works in images that have no /bin/sh. Use CMD-SHELL only when you need pipes, && or variable expansion.
Minimal and distroless images often lack curl, wget and even a shell. You have three ways to probe them:
| Option | Benefit | Cost |
|---|---|---|
| Use a different probe already in the image | No image changes | May only check something weaker than readiness |
| Bundle a small static probe binary | Precise check at the protocol level | Adds size and more code to patch |
| Have the app expose a health endpoint or subcommand it can call on itself | Tests real readiness logic | You write and maintain it |
Each probe tool you add makes the image larger and gives an attacker more to work with. Leaving tools out means more custom work in your own code.
Aim for the right strength. A probe that only confirms the process is running or the port is open passes before the service can handle requests, so the startup race comes back. A probe that also checks downstream dependencies is too strict. When a shared database becomes slow, every service that checks it turns unhealthy together, and one degraded component turns into a stack-wide failure. Check only that this service can do its own work.
services:
postgres:
image: postgres:16
environment:
POSTGRES_PASSWORD: example-only
healthcheck:
# Exec form, protocol-level probe. -h 127.0.0.1 forces TCP, so the
# socket-only temporary server used during init does not pass early.
test: ["CMD", "pg_isready", "-h", "127.0.0.1", "-U", "postgres"]
interval: 5s
retries: 10
mysql:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: example-only
healthcheck:
# Asks the server itself, over TCP, instead of only checking that a port is open.
test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1"]
interval: 5s
retries: 10
redis:
image: redis:7
healthcheck:
# CMD-SHELL only because a pipe is needed to require an actual PONG reply.
test: ["CMD-SHELL", "redis-cli ping | grep -q PONG"]
interval: 5s
retries: 10
api:
image: example/api:1.0 # distroless: no shell, curl or wget
healthcheck:
# The app's own subcommand checks its own readiness only,
# not postgres or redis, so a slow dependency does not cascade.
test: ["CMD", "/app/server", "healthcheck"]
interval: 10s
retries: 5
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
Readiness healthchecks that use each image's own client tool in exec form, with CMD-SHELL used only where a pipe is required, and a distroless app that checks itself through its own health subcommand instead of a bundled curl.
How should you size interval, timeout, retries and start_period?
Each field controls one part of the probe loop:
interval: how long Docker waits between probes.timeout: how long a single probe may run before it counts as a failure.retries: how many consecutive failures mark the container unhealthy.start_period: a grace window after the container starts. Failures inside it do not count towardretries, but one success marks the container healthy immediately.
Because an early success ends the grace window, you can make start_period generous without slowing a fast boot. Size it to the slowest first start you expect, such as Postgres initializing a fresh data directory on a loaded CI runner. Then let retries and interval decide how quickly a broken service fails after that window.
Illustrative estimate (assumed numbers, not a benchmark). Assume interval 5s, timeout 3s, retries 5 and start_period 60s.
- Worst-case time to unhealthy: about
start_period + retries × (interval + timeout), which is 60 + 5 × (5 + 3) = 100s. - Detection lag: each
service_healthygate adds up to oneintervalbetween "actually ready" and "reported healthy." Three gates in a chain add up to 3 × 5s = 15s of startup latency.
A shorter interval reduces that lag, but the probe keeps running for the container's whole lifetime, not only during startup. A 1s interval means one process spawn, and often one database connection, every second per container.
Poor sizing produces flapping in two common ways:
timeoutset too close to normal probe time. On a busy host, slow probes time out intermittently.retriesset to 1. A single slow probe marks the container unhealthy, which fails every dependent waiting on it.
services:
db:
image: postgres:16
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: example-only-change-me
POSTGRES_DB: appdb
healthcheck:
# pg_isready is cheap and exits non-zero until the server accepts connections
test: ["CMD-SHELL", "pg_isready -U app -d appdb"]
interval: 5s # gap between probes; also the max detection lag per gate
timeout: 3s # well above normal probe time so a busy host does not cause flapping
retries: 5 # tolerate a few slow probes instead of failing on one
start_period: 60s # sized for a fresh data-dir init on a slow CI runner;
# a single early success marks it healthy, so fast boots are not delayed
api:
image: example/api:1.0 # placeholder; assumes the app ships a healthcheck subcommand
depends_on:
db:
condition: service_healthy # gate 1: waits up to ~1 interval after db is ready
healthcheck:
test: ["CMD", "/app/server", "healthcheck"]
interval: 5s
timeout: 3s
retries: 5
start_period: 30s # app boot is faster than a db init, so a shorter grace window
web:
image: example/web:1.0 # placeholder
depends_on:
api:
condition: service_healthy # gate 2: adds up to another interval of lag
A Compose file that sizes db and api healthchecks with the section's assumed values, using a generous start_period for slow first boots and a two-gate service_healthy chain whose detection lag is bounded by each interval.
Worked example: Postgres, a migration job and an API gated in sequence
The stack has three services. db runs Postgres with a healthcheck that calls pg_isready against the application database and user, not just the server process. migrate runs the schema migration tool once and exits. It declares depends_on: db with condition: service_healthy. api declares depends_on: migrate with condition: service_completed_successfully. It does not depend on db directly, because migrate cannot have succeeded without a working database.
The success path
On docker compose up, Compose creates and starts db first. Its health status begins as starting. Compose polls it and holds migrate back until the status flips to healthy. migrate then runs, applies its changes, and exits with code 0. Only after that exit does Compose start api. The API therefore never runs against a missing or half-migrated schema, and its startup logic doesn't need to know migrations exist.
Postgres never becomes healthy
Suppose the configured credentials don't match the database. Then pg_isready keeps failing. After start_period elapses, each failure counts toward retries, and once retries run out the container is marked unhealthy. Until that point Compose is simply waiting, which in attached mode looks like a hang with Postgres logs scrolling past. When the status turns unhealthy, Compose reports that the dependency failed and does not start migrate or api.
The migration exits non-zero
If a migration fails, migrate exits with a non-zero code. Compose treats that as an unmet service_completed_successfully condition, refuses to start api, and up fails. The error message names migrate. The real cause is in that container's logs, so check them first with docker compose logs migrate.
How do you debug a Compose stack that hangs or exits on startup?
Start-up debugging follows the same path every time, which is the main payoff of gating on health. A race that used to fail one run in ten now fails the same way every run, at a named service, with recorded evidence.
Read the state first
docker compose ps -a lists every service, including ones that have already exited. The STATUS column tells you which of three cases you're in:
(health: starting)means the probe hasn't passed yet.(unhealthy)means the probe passed its retry budget without succeeding.Exited (N)gives you the process exit code, which is the number aservice_completed_successfullycondition checks.
Then read the probe's own output
Run docker inspect on the container and look at State.Health. It holds the current status, a FailingStreak counter and a log of the most recent probe runs. Each probe run records its exit code and its output. Three patterns are worth recognising:
- Missing probe binary. Every log entry fails the same way. The output says the executable was not found, or a shell probe exits with 127. Postgres itself is fine. The image just doesn't ship
curlorpg_isready. start_periodtoo short. The early entries show "connection refused". Then the dependent service gives up. A minute later,psreports the dependency ashealthy. Increasestart_period, notretries.- Broken dependency.
FailingStreakkeeps climbing, and the container's logs show the cause, such as bad credentials, a full volume or a failed config parse.
Each pattern points to a different fix. You can tell them apart from recorded output instead of rerunning the stack and hoping it fails again.
How can healthcheck gating save engineering time?
Most of the time saved comes from removing work that intermittent startup failures create. None of it shows up as a feature, so it is easy to miss.
- Fewer reruns and less flake triage. An intermittent CI failure caused by timing usually leads to a rerun, and repeated failures lead someone to investigate a test that is not actually broken. With gating, a cold runner waits instead of failing, and a real dependency problem fails at a named service every time.
- Faster diagnosis when something is broken. Health status,
FailingStreakand the stored probe output show which service failed and why, so you don't need to reproduce a race. - Less custom startup code to maintain. Wait scripts, sleep loops and per-image entrypoint wrappers become unnecessary inside Compose. The readiness rule lives in one place, in the Compose file, where reviewers can see it.
- Smoother onboarding. A new teammate's first
docker compose up, with its slow database initialization, works without tribal knowledge such as "run it twice" or "start the database first." - No over-padded sleeps. A fixed sleep has to cover the slowest case on every run. A healthcheck ends the wait as soon as the dependency is ready.
Illustrative estimate (assumed inputs, not a measured result). Assume a team runs 200 pipeline jobs a week, 3% of them fail because of a startup race, and each failure costs an engineer 15 minutes to notice, rerun and confirm it was a flake. That is 6 failures × 15 minutes, or about 90 minutes a week. If the same stack also used a fixed 20-second sleep where gating would typically wait 5 seconds, the assumed 200 jobs would spend about 50 extra minutes of runner time each week. Plug in your own job counts and failure rates. The structure of the calculation matters more than these particular numbers.
What are the alternatives, and why do apps still need retry logic?
The older alternative is a wait-for-it-style script or a sleep loop in the container's entrypoint. Both are weaker than a healthcheck. A wait-for-it script usually only confirms that a TCP port accepts connections. Postgres can be listening while it still rejects clients during startup or recovery. A protocol-level check such as pg_isready or a real query catches that state. The script also moves orchestration logic into the image: the entrypoint must know dependency hostnames and ship a shell and the script itself. Inside Compose, a healthcheck with condition: service_healthy does the same job in the Compose file, so the script is mostly unnecessary.
| Approach | What it verifies | Where the logic lives | Handles failures after startup |
|---|---|---|---|
| Sleep loop | Only that time has passed | Entrypoint | No |
| wait-for-it script | TCP port is open | Entrypoint | No |
Healthcheck + service_healthy |
Whatever the test command checks | Compose file | No, it gates startup only |
| App retries with backoff | Each real operation | Application code | Yes |
Healthcheck gating covers only initial startup. A database can restart mid-run. When a dependency later turns unhealthy, Compose does not restart or stop the services that depend on it. A passing check also does not guarantee that every client operation will succeed, because connection limits, locks and network blips still occur. depends_on conditions exist only in Compose, and other orchestrators use their own readiness mechanisms. A stack that relies on gating alone can hide missing retry logic until it reaches production.
Healthchecks cost little to add, so make them the default for local and CI stacks. Anything that runs outside Compose still needs retries with backoff.
Who should use depends_on with healthchecks?
Gating fits any team that runs multi-service stacks with Docker Compose and has hit, or expects to hit, startup races:
- Teams running integration or end-to-end tests in CI against real databases, caches or brokers started from Compose. Cold runners are where races show up most.
- Developers maintaining a local development stack that others clone and start, especially one with a database that initializes a fresh volume on first run.
- Projects with one-shot setup steps such as schema migrations, seed data or bucket and queue creation.
service_completed_successfullyturns these into explicit pipeline steps. - Stacks with a clear chain of stateful dependencies, where a service cannot do useful work until something upstream is ready.
If a stack has a single service, or only stateless services that tolerate each other being absent, there is little to gain.
When should you avoid or limit it?
Healthcheck gating is not always the right tool, and overusing it has costs.
- As a substitute for retry logic. If the application cannot survive a dependency restart, gating hides the gap locally and it shows up in production. Treat gating as an addition to retries, not a replacement.
- Outside Compose.
depends_onconditions are a Compose feature. Kubernetes and other orchestrators use their own readiness and startup mechanisms, so don't design production behaviour around Compose ordering. - When there is no meaningful probe. If the only check available is "the port is open" and the image cannot run a better one,
service_healthyadds waiting without adding much certainty. Useservice_startedand rely on application retries, or invest in a proper health subcommand first. - For dependencies that are genuinely optional. If a service can start and degrade gracefully without, say, a metrics backend or a mail mock, gating on that backend's health only slows startup and couples failures together.
- In long chains where every hop is gated. Each
service_healthyedge adds detection lag, and one slow or flapping service blocks everything downstream. Gate only on dependencies that a service truly needs at startup, as the worked example does by havingapidepend onmigrateinstead of on bothmigrateanddb. - With expensive probes. A healthcheck runs for the container's whole lifetime. A probe that runs a heavy query or opens a new connection every second costs resources long after startup is over. Keep probes cheap, or lengthen the interval.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to docker compose depends_on healthcheck, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.