depends_on & Startup Order
When you run docker compose up, Compose has to decide in which order to create and start the services. Without
any hints it starts them all at once. depends_on adds edges to that picture: "start db before api", or, much
more useful, "start api only once db is healthy". This lesson covers the short and long syntax, the three
conditions, the restart and required options, the errors Compose detects, and how to think about readiness. The
Docker course introduces the idea in depends_on & Healthchecks; here we go through every
option.
db ──healthy──▶ migrate ──completed (exit 0)──▶ api ──started──▶ web
└──────────────────healthy──────────────────────┘Short syntax: order only
A list of service names. Compose starts those services first, but it waits only until their containers are started, not until the programs inside are ready:
services:
api:
image: shop/api:1.4
depends_on:
- db
- cache
db:
image: postgres:18
cache:
image: redis:8name: demo
services:
api:
image: shop/api:1.4
networks:
default: null
depends_on:
cache:
condition: service_started
required: true
db:
condition: service_started
required: true
cache:
image: redis:8
networks:
default: null
db:
image: postgres:18
networks:
default: null
networks:
default:
name: demo_default
The normal form shows what the short list means: condition: service_started and required: true for each
dependency. Postgres needs a few seconds after its container starts before it accepts connections, so an API that
connects at startup may still crash. That's what the long syntax is for.
Long syntax: conditions
| Condition | Compose waits until the dependency… | Typical use |
|---|---|---|
service_started |
container is running (the default) | loose coupling; the app retries itself |
service_healthy |
reports healthy (healthcheck required) | databases, brokers |
service_completed_successfully |
has exited with code 0 | migrations, seeding, one-time setup |
services:
web:
image: shop/web:1.4
depends_on:
api:
condition: service_healthy
api:
image: shop/api:1.4
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8000/health"]
interval: 5s
depends_on:
db:
condition: service_healthy
restart: true
migrate:
condition: service_completed_successfully
metrics:
condition: service_started
required: false
migrate:
image: shop/api:1.4
command: ["python", "manage.py", "migrate"]
depends_on:
db:
condition: service_healthy
db:
image: postgres:18
environment:
POSTGRES_PASSWORD: dev
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 2s
retries: 15
metrics:
image: prom/statsd-exporter:v0.28.0
profiles: [monitoring]name: demo
services:
api:
image: shop/api:1.4
networks:
default: null
depends_on:
db:
condition: service_healthy
restart: true
required: true
metrics:
condition: service_started
required: false
migrate:
condition: service_completed_successfully
required: true
healthcheck:
test:
- CMD
- wget
- -qO-
- http://127.0.0.1:8000/health
interval: 5s
db:
environment:
POSTGRES_PASSWORD: dev
image: postgres:18
networks:
default: null
healthcheck:
test:
- CMD-SHELL
- pg_isready -U postgres
interval: 2s
retries: 15
migrate:
command:
- python
- manage.py
- migrate
image: shop/api:1.4
networks:
default: null
depends_on:
db:
condition: service_healthy
required: true
web:
image: shop/web:1.4
networks:
default: null
depends_on:
api:
condition: service_healthy
required: true
networks:
default:
name: demo_default
Two extra options appeared:
restart: true: when Compose restarts or recreatesdb(for example after you change its config and runup -d), it restartsapias well, so the API reconnects cleanly. It applies to Compose operations, not to a crash handled by the engine's restart policy.required: false: the dependency is optional.metricsis only enabled with themonitoringprofile; without it, it disappears from the project and Compose simply skips the edge. Withrequired: true(the default) that would be an error, as the next section shows.
Errors Compose detects
A dependency on a service that doesn't exist (a typo, or a service only enabled by a profile):
services:
api:
image: shop/api:1.4
depends_on: [db, cache]
db:
image: postgres:18service "api" depends on undefined service "cache": invalid compose project
A cycle, which can't be ordered at all:
services:
api:
image: shop/api:1.4
depends_on: [worker]
worker:
image: shop/worker:1.4
depends_on: [api]dependency cycle detected: api -> worker -> api
An unknown condition fails schema validation:
services:
api:
image: shop/api:1.4
depends_on:
db:
condition: service_ready
db:
image: postgres:18validating /home/ada/demo/compose.yaml: services.api.depends_on.db.condition value must be one of 'service_started', 'service_healthy', 'service_completed_successfully'
What config can not see is a service_healthy condition on a service with
no healthcheck, because the healthcheck may come from the image. up then fails:
$ docker compose up -d
[+] Running 2/2
✔ Network demo_default Created 0.1s
✔ Container demo-db-1 Started 0.3s
dependency failed to start: container demo-db-1 has no healthcheck configured(Sample output.) A dependency that becomes unhealthy, or a migrate job that exits non-zero, stops the
dependents the same way, with dependency failed to start: container demo-migrate-1 exited (1).
Order: a topological sort
Compose starts services in an order where every dependency comes before its dependents, and stops them in the
reverse order (down stops web before api before db). Services that don't depend on each other start in
parallel. docker compose up api starts api and everything it depends on; --no-deps skips them.
The model computes start "waves" from the dependency graph and then simulates the wait, using each service's start time and how long it takes to become healthy or to finish:
deps = {
"web": {"api": "service_healthy"},
"api": {"db": "service_healthy", "migrate": "service_completed_successfully"},
"migrate": {"db": "service_healthy"},
"db": {},
"cache": {},
}
# seconds from container start until: running, healthy, or exited 0
timing = {"db": {"healthy": 6}, "migrate": {"completed": 4}, "api": {"healthy": 3},
"web": {}, "cache": {}}
def waves(deps):
done, result = set(), []
while len(done) < len(deps):
ready = sorted(s for s in deps if s not in done and set(deps[s]) <= done)
if not ready:
raise ValueError("dependency cycle detected")
result.append(ready)
done.update(ready)
return result
def simulate(deps, timing):
ready_at = {} # service -> {condition: time}
for wave in waves(deps):
for s in wave:
start = max([ready_at[d][cond] for d, cond in deps[s].items()], default=0)
t = timing[s]
ready_at[s] = {
"service_started": start,
"service_healthy": start + t.get("healthy", 0),
"service_completed_successfully": start + t.get("completed", 0),
}
waits = ", ".join(f"{d} {c.removeprefix('service_')}" for d, c in deps[s].items()) or "nothing"
print(f"t={start:>2}s start {s:8} (waited for: {waits})")
return ready_at
print("waves:", waves(deps))
simulate(deps, timing)waves: [['cache', 'db'], ['migrate'], ['api'], ['web']]
t= 0s start cache (waited for: nothing)
t= 0s start db (waited for: nothing)
t= 6s start migrate (waited for: db healthy)
t=10s start api (waited for: db healthy, migrate completed_successfully)
t=13s start web (waited for: api healthy)
db and cache start immediately in the first wave. migrate waits 6 s for a healthy database, api waits for the
migration to finish (t = 10 s), and web for a healthy API at t = 13 s.
depends_on is not a substitute for resilience
depends_on only acts while Compose is starting things. Once the app is running, a database restart, a network
blip or a failover is invisible to it. Write services that retry their connections with a back-off, and use
depends_on with health conditions to make startup smooth, not to guarantee correctness. In
Kubernetes and Swarm there is no depends_on at all for
exactly this reason; readiness probes and retries do the job.
Learn more: Healthchecks · Restart Policies · Profiles
Test yourself
What does the short form depends_on: [db] wait for?
- db to be healthy
- db's container to be started
- db to exit successfully
- Nothing; it is only documentation
Which condition fits a one-off database migration job?
- service_started
- service_healthy
- service_completed_successfully
- required: false
api depends on metrics, which is only in the monitoring profile. Without that profile, what does docker compose config report?
- Nothing; metrics starts anyway
- service "api" depends on undefined service "metrics", unless the dependency has required: false
- A warning only
- It enables the profile automatically