Compose startup dependencies
- Version
- 29
- Review
- Draft
Summary#
depends_on orders service startup. Its long form can wait for a dependency to be healthy or for a one-off task to exit successfully. The short form waits only until the dependency has started.
Syntax#
services:
db:
image: db-image
migrate:
image: migration-image
app:
image: app-image
depends_on:
db:
condition: service_healthy
migrate:
condition: service_completed_successfully
The database image or service definition must provide the health check.
Example#
The example uses a local alpine:3 image.
(
set -eu
project="dlr-docker-commands-deps-$$"
dir=$(mktemp -d)
compose() {
docker compose --progress quiet --project-name "$project" \
--file "$dir/compose.yaml" "$@"
}
trap 'compose down --volumes --timeout 1 >/dev/null 2>&1 || true; rm -rf -- "$dir"' EXIT
cat > "$dir/compose.yaml" <<'EOF'
services:
db:
image: alpine:3
pull_policy: never
init: true
command: ["sh", "-c", "sleep 2; echo 'db ready' >> /shared/events; touch /tmp/ready; exec sleep 60"]
volumes: ["shared:/shared"]
healthcheck:
test: ["CMD", "test", "-f", "/tmp/ready"]
interval: 1s
retries: 10
migrate:
image: alpine:3
pull_policy: never
command: ["sh", "-c", "echo 'migration done' >> /shared/events"]
volumes: ["shared:/shared"]
depends_on:
db:
condition: service_healthy
app:
image: alpine:3
pull_policy: never
command: ["sh", "-c", "echo 'app started' >> /shared/events; cat /shared/events"]
volumes: ["shared:/shared"]
depends_on:
migrate:
condition: service_completed_successfully
volumes:
shared:
EOF
compose run --rm -T app
compose ps --all --format '{{.Service}} {{.State}} {{.ExitCode}}' | sort
)
Expected output#
db ready
migration done
app started
db running 0
migrate exited 0
Common mistakes#
A list such as depends_on: [db] does not wait for the database to accept connections. Add a health check that tests readiness and use condition: service_healthy. Applications still need to reconnect if a dependency fails later.
Version applicability#
Checked with Docker Engine 29 and Docker Compose 5. Since Compose 2.20.0, required: false makes an unavailable dependency a warning. Since 2.17.0, dependency restart: true restarts the dependent service when Compose explicitly restarts or updates its dependency.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0