Introduction
Container start order in Docker Compose is not the same as service readiness. A database container can be running while PostgreSQL is still initializing its data directory and rejecting TCP connections, which causes application containers that started a second later to fail on their first connection attempt. The reliable fix is to define a healthcheck on the dependency and use the long-form depends_on syntax with condition: service_healthy, so Compose waits for a passing health status before starting dependent services. For one-shot tasks such as schema migrations, condition: service_completed_successfully gates startup on a zero exit code instead of a running process.
Why Container Start Order Is Not Service Readiness
When you run docker compose up, Compose creates and starts containers according to the dependency graph. Starting a container means the container runtime has launched its main process. It does not mean the process inside that container is ready to accept work. A PostgreSQL container may report as running while it is still replaying WAL files, running initialization scripts in /docker-entrypoint-initdb.d, or binding its listening socket. A Redis container may be up before it has loaded an append-only file. An HTTP API may have started its process before it has loaded configuration, warmed caches, or established downstream connections.
This gap is the source of most “works on my machine, fails in CI” startup failures. On a developer laptop, the database often already has a warm volume and becomes ready quickly. In a clean CI environment, the same stack starts from an empty volume, initialization takes longer, and the application hits a connection refused error before the database is ready. The failure looks intermittent because it depends on timing, disk speed, image pull state, and host load.
The short-form depends_on syntax only expresses start order. It tells Compose to start db before api, but it does not wait for PostgreSQL to accept queries. That behavior is correct for the container lifecycle, but insufficient for application readiness. Healthchecks close that gap by giving Compose an observable signal: a command that returns success only when the service can actually do its job.
# Short form: start order onlyservices: api: image: my-api:latest depends_on: - db db: image: postgres:16-alpineThe configuration above guarantees that Compose starts db before api. It does not guarantee that api can connect to db at startup.
Compose File Format and CLI Behavior
The examples in this article use the Compose Specification format and the docker compose CLI, which is the Docker Compose v2 plugin shipped as a Docker CLI extension. The legacy docker-compose v1 Python binary has reached end of life and should not be used for new projects. You can confirm which CLI you have installed with the following commands.
docker compose version# Docker Compose version v2.29.7
docker version --format '{{.Server.Version}}'# 27.3.1Modern Compose files do not require a top-level version field. Older tutorials often include version: "3.8" or version: "3.9", but that field is obsolete in current Compose implementations. The file name can be compose.yaml, compose.yml, docker-compose.yaml, or docker-compose.yml. I recommend compose.yaml because it is the preferred default name in the Compose Specification.
The depends_on long syntax with condition is part of the Compose Specification. It supports service_started, service_healthy, and service_completed_successfully. If you are maintaining an older project that still uses docker-compose v1 behavior, verify the runtime before relying on these conditions. The behavior described here assumes the docker compose v2 plugin.
Defining Healthchecks That Reflect Real Readiness
A healthcheck is a command Docker runs periodically inside the container. If the command exits with code 0, the container is considered healthy. If it exits with code 1, the check fails. Exit code 2 is reserved and should not be used by healthcheck commands. Docker tracks the health status as starting, healthy, or unhealthy based on the configured intervals and retry count.
The healthcheck definition can live in the image Dockerfile or in compose.yaml. Defining it in compose.yaml is useful when you want environment-specific checks, when the image does not include a check, or when you need to override an image default. Compose service-level healthchecks override image-level healthchecks.
| Key | Purpose | Typical value |
|---|---|---|
test | Command to execute | ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"] |
interval | Time between checks | 5s to 30s |
timeout | Maximum time for a single check | 3s to 10s |
retries | Consecutive failures before unhealthy | 3 to 10 |
start_period | Grace period for container startup | 5s to 60s |
start_interval | Check interval during start_period (Docker Engine 25.0+) | 1s to 5s |
The test field accepts two main forms. The exec form, ["CMD", "redis-cli", "ping"], runs the command directly without a shell. The shell form, ["CMD-SHELL", "curl -fsS http://localhost:8000/health || exit 1"], runs through /bin/sh -c and supports shell features such as pipes, environment variable expansion, and ||. Use the exec form when possible because it avoids shell parsing. Use the shell form when you need shell behavior.
The start_period value deserves careful attention. During the start period, healthcheck failures do not count toward the retries limit. A single successful check ends the start period. This setting prevents slow-starting services from being marked unhealthy before they have had a chance to initialize. Setting it too low causes false unhealthy states. Setting it too high delays failure detection when a service is genuinely broken.
PostgreSQL Healthcheck
PostgreSQL images include pg_isready, which checks whether the server accepts connections. The common mistake is running pg_isready without specifying the user and database, which can produce misleading failures or log noise depending on the image defaults.
services: db: image: postgres:16-alpine environment: POSTGRES_DB: appdb POSTGRES_USER: appuser POSTGRES_PASSWORD: change-me-in-dev healthcheck: test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"] interval: 5s timeout: 3s retries: 10 start_period: 10sThe double dollar sign ($$) escapes variable expansion so Compose passes $POSTGRES_USER to the container shell instead of expanding it on the host. If you use a single $, Compose tries to substitute the value from the host environment or .env file at parse time.
Redis Healthcheck
Redis provides a simple PING command. The redis-cli ping command returns PONG and exits with code 0 when the server is ready.
services: redis: image: redis:7-alpine command: ["redis-server", "--appendonly", "yes"] healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 5s timeout: 3s retries: 5 start_period: 5sHTTP Application Healthcheck
For HTTP services, check a dedicated health endpoint that returns a fast, lightweight response. Avoid hitting endpoints that trigger database queries, external API calls, or heavy computation unless you explicitly want those dependencies included in the readiness signal.
services: api: build: ./api healthcheck: test: ["CMD-SHELL", "python -c \"import urllib.request; urllib.request.urlopen('http://localhost:8000/health', timeout=2)\""] interval: 10s timeout: 3s retries: 5 start_period: 15sThis example uses Python’s standard library because many slim Python images do not include curl or wget. If your image includes curl, the equivalent check is ["CMD-SHELL", "curl -fsS http://localhost:8000/health || exit 1"]. The -f flag makes curl return a non-zero exit code on HTTP error responses, and -sS keeps output quiet on success while still showing errors.
depends_on Conditions in Practice
The long-form depends_on syntax lets you specify the condition Compose should wait for. Each condition fits a different dependency type.
| Condition | Waits for | Typical use |
|---|---|---|
service_started | Container has started | Dependencies where process start is enough, or where the app has its own retry logic |
service_healthy | Healthcheck reports healthy | Databases, caches, queues, HTTP APIs |
service_completed_successfully | Container exits with code 0 | Migrations, seed jobs, certificate generation, one-shot setup tasks |
The service_started condition is the default. It is equivalent to the short-form syntax. It is useful when the dependency does not expose a meaningful healthcheck or when the consuming application already implements connection retries with backoff. It is not sufficient for dependencies that accept connections only after a warmup phase.
The service_healthy condition requires the dependency to define a healthcheck. If you set condition: service_healthy on a service that has no healthcheck, Compose cannot evaluate the condition and reports an error. This condition is the right choice for most long-running infrastructure dependencies.
The service_completed_successfully condition is designed for init containers. A migration container runs, applies schema changes, exits with code 0, and then the API starts. If the migration exits with a non-zero code, Compose marks the dependency as failed and does not start the dependent service.
services: api: build: ./api depends_on: db: condition: service_healthy redis: condition: service_healthy migrate: condition: service_completed_successfullyRecent Compose Specification implementations also support a restart: true attribute under a depends_on dependency. When set, Compose restarts the dependent service if the dependency is updated or restarted. This can be useful in development workflows, but it requires a Compose implementation that supports the attribute. If you target older environments, test it explicitly before relying on it.
A Complete Multi-Service Example
The following example shows a small stack with a Python API, PostgreSQL, Redis, and a one-shot migration service. The structure is intentionally simple so you can run it locally and adapt the pattern to your own project.
compose-healthcheck-demo/├── compose.yaml├── .env├── api/│ ├── Dockerfile│ ├── requirements.txt│ ├── main.py│ └── manage.pyThe .env file holds development credentials. In a real deployment, keep secrets out of shell environment files committed to source control and use a secret manager or Docker secrets where appropriate.
POSTGRES_DB=appdbPOSTGRES_USER=appuserPOSTGRES_PASSWORD=change-me-in-devThe API image uses Python 3.12 on a slim Debian base. The Dockerfile installs dependencies and copies the application code.
FROM python:3.12-slim
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1ENV PYTHONUNBUFFERED=1
COPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000The requirements.txt file pins the application dependencies.
fastapi==0.115.0uvicorn==0.30.6psycopg[binary]==3.2.1redis==5.0.8The application exposes a health endpoint. In a production service, this endpoint should check only what the load balancer or orchestrator needs to know. A shallow health check confirms the process is responding. A deeper readiness check can verify database connectivity, but you should be deliberate about that choice because a database outage can then mark every API instance as not ready.
import osfrom fastapi import FastAPI
app = FastAPI()
@app.get("/health")def health(): return {"status": "ok", "service": os.getenv("SERVICE_NAME", "api")}The migration script is a placeholder for a real migration command such as alembic upgrade head, python manage.py migrate, or prisma migrate deploy. The important behavior for Compose is the exit code: zero means success, non-zero means failure.
import sys
def migrate() -> None: print("Running database migrations...") # Replace with your real migration command. print("Migrations complete.")
if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] == "migrate": migrate() sys.exit(0) print(f"Unknown command: {sys.argv[1:]}", file=sys.stderr) sys.exit(1)The Compose file wires the services together. PostgreSQL and Redis expose healthchecks. The migration service waits for a healthy database and runs once. The API waits for healthy infrastructure and a successful migration.
name: compose-healthcheck-demo
services: db: image: postgres:16-alpine environment: POSTGRES_DB: ${POSTGRES_DB} POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} volumes: - pgdata:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"] interval: 5s timeout: 3s retries: 10 start_period: 10s
redis: image: redis:7-alpine command: ["redis-server", "--appendonly", "yes"] healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 5s timeout: 3s retries: 5 start_period: 5s
migrate: build: context: ./api command: ["python", "manage.py", "migrate"] environment: DATABASE_URL: postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB} depends_on: db: condition: service_healthy restart: "no"
api: build: context: ./api command: ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"] ports: - "8000:8000" environment: DATABASE_URL: postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB} REDIS_URL: redis://redis:6379/0 SERVICE_NAME: api depends_on: db: condition: service_healthy redis: condition: service_healthy migrate: condition: service_completed_successfully healthcheck: test: ["CMD-SHELL", "python -c \"import urllib.request; urllib.request.urlopen('http://localhost:8000/health', timeout=2)\""] interval: 10s timeout: 3s retries: 5 start_period: 15s
volumes: pgdata:Start the stack and observe the startup sequence. The --wait flag is useful in CI because it waits until services are healthy or have exited successfully, then returns a non-zero exit code on failure.
docker compose up -d --build --waitdocker compose psdocker compose logs --tail=50 migratecurl -fsS http://localhost:8000/healthThe docker compose ps output shows the health status for services that define a healthcheck. A healthy stack looks like this.
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTScompose-healthcheck-demo-api-1 compose-healthcheck-demo-api "python -m uvicorn m…" api 30 seconds ago Up 20 seconds (healthy) 0.0.0.0:8000->8000/tcpcompose-healthcheck-demo-db-1 postgres:16-alpine "docker-entrypoint.s…" db 30 seconds ago Up 29 seconds (healthy) 5432/tcpcompose-healthcheck-demo-migrate-1 compose-healthcheck-demo-migrate "python manage.py mi…" migrate 30 seconds ago Exited (0) 22 seconds agocompose-healthcheck-demo-redis-1 redis:7-alpine "docker-entrypoint.s…" redis 30 seconds ago Up 29 seconds (healthy) 6379/tcpWhen you are done, remove the containers and volumes.
docker compose down -vStartup Ordering Patterns Beyond depends_on
depends_on with healthchecks is a strong default for local development, integration tests, and simple Compose deployments. It is not a complete startup strategy for every system. You still need to understand where it helps and where it stops.
Application-level retries are the most important companion pattern. Even if the database is healthy when the API starts, the database can become unavailable later because of a restart, network issue, failover, or maintenance event. Compose does not restart dependent services when a dependency becomes unhealthy after startup unless you have configured additional behavior explicitly. Your application should handle transient connection failures with bounded retries, backoff, and clear logging.
Init containers and one-shot jobs are a good fit for service_completed_successfully. Migrations, schema checks, seed data, and certificate generation belong in this category. Keep these jobs idempotent. A migration that runs twice during a flaky deployment should produce a predictable result, either by doing nothing on the second run or by failing with a clear message.
Wait scripts and wrapper entrypoints are another option. Tools like a small shell script that polls a TCP port or HTTP endpoint can block startup until a dependency responds. The trade-off is maintenance: you now own another startup mechanism, and it can duplicate or conflict with the healthcheck logic. I prefer native Compose healthchecks for Compose-managed dependencies because the readiness signal is visible through docker compose ps and docker inspect. A wrapper script can still be useful when you need to wait for an external dependency that is not managed by the same Compose project.
For production orchestration, the concepts map differently. Kubernetes uses liveness, readiness, and startup probes, and those probes control traffic routing and container restarts in ways that are more granular than Compose. Docker Swarm has its own scheduling behavior. Treat Compose startup ordering as a local and CI orchestration tool, not as a universal replacement for application resilience.
Observing and Debugging Startup Behavior
When startup ordering fails, inspect the dependency state before changing random timeouts. Compose gives you several useful commands for this.
# Show service state, health, and published portsdocker compose ps
# Stream logs for selected servicesdocker compose logs -f db migrate api
# Inspect the raw healthcheck historydocker inspect --format '{{json .State.Health}}' compose-healthcheck-demo-db-1 | jq
# Check exit code for a one-shot jobdocker inspect --format '{{.State.ExitCode}}' compose-healthcheck-demo-migrate-1The docker inspect health output includes the recent check results, exit codes, and command output. This is often faster than guessing why a service is unhealthy. If the healthcheck command itself is failing because a binary is missing, the output will show it.
For CI pipelines, docker compose up -d --build --wait --wait-timeout 120 gives you a bounded wait. If the stack does not become ready within the timeout, the command exits with an error and you can dump logs for diagnosis.
set -euo pipefail
docker compose up -d --build --wait --wait-timeout 120 || { echo "Compose stack did not become ready" docker compose ps docker compose logs --no-color --tail=200 exit 1}Troubleshooting Common Failures
Dependency Failed to Start Because the Container Is Unhealthy
The most common failure when using condition: service_healthy looks like this:
dependency failed to start: container compose-healthcheck-demo-db-1 is unhealthyThis message means Compose waited for the dependency healthcheck, but the check never reached a healthy state within the configured retry window. Start by checking the health log and service logs.
docker compose psdocker inspect --format '{{json .State.Health}}' compose-healthcheck-demo-db-1 | jqdocker compose logs --tail=100 dbCommon causes include a database initialization that takes longer than start_period, a healthcheck command that points at the wrong port, missing credentials in the check command, or an application that listens on 127.0.0.1 inside the container while the check expects another interface. Fix the underlying healthcheck, not just the symptom. Increasing retries can mask a slow startup, but it can also hide a broken configuration.
pg_isready Reports the Wrong Default Role
When pg_isready runs without an explicit user, it may default to the container process user. In PostgreSQL images, this often produces log noise or failed checks that look like authentication problems.
FATAL: role "root" does not existYou can confirm this by inspecting the database logs. The fix is to pass the correct user and database in the healthcheck command.
healthcheck: test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"] interval: 5s timeout: 3s retries: 10 start_period: 10sIf your database requires a different readiness signal, such as verifying a specific schema or running a simple query, you can use psql instead. Keep the command lightweight because it runs repeatedly.
healthcheck: test: ["CMD-SHELL", "psql -U $$POSTGRES_USER -d $$POSTGRES_DB -c 'SELECT 1' >/dev/null"] interval: 10s timeout: 5s retries: 5 start_period: 20sHealthcheck Binary Missing in the Image
Minimal images often do not include curl or wget. A healthcheck that assumes those binaries exist fails immediately.
OCI runtime exec failed: exec failed: unable to start container process: exec: "curl": executable file not found in $PATH: unknownYou can verify the failure in the container health log with docker inspect. The fix is to use a tool that exists in the image, install the required package in the Dockerfile, or use a language runtime already present in the container. For Python images, python -c with urllib.request is a practical option. For Node.js images, node -e with http.get works. For Alpine-based images, wget -qO- is often available, but you should confirm the exact image contents rather than assume.
healthcheck: test: ["CMD-SHELL", "wget -qO- http://localhost:3000/health >/dev/null || exit 1"]Application Starts Before the Database Accepts Connections
If you only use the short-form depends_on, or if the application has no retry logic, you may see connection errors during startup even though both containers are running.
psycopg.OperationalError: connection failed: Connection refused Is the server running on that host and accepting TCP/IP connections?This error means the application reached the database host and port, but nothing accepted the connection. In Compose, the usual fix is to add a proper database healthcheck and switch the application dependency to condition: service_healthy. You should also keep application-level retry logic for runtime resilience. A service that can only start during a perfect startup window will be fragile during restarts and deployments.
Migration Job Fails and Blocks the API
When an API depends on migrate with condition: service_completed_successfully, a failed migration stops the startup chain. That behavior is desirable because running an API against an incompatible schema can cause worse failures. The signal looks like a dependency failure, and the migration logs contain the real cause.
docker compose psdocker compose logs --tail=200 migratedocker inspect --format '{{.State.ExitCode}}' compose-healthcheck-demo-migrate-1If the exit code is non-zero, fix the migration issue, rerun the job, and confirm it is idempotent. A common mistake is writing migrations that fail when a column already exists or when seed data has already been inserted. Idempotent migrations make startup recovery predictable.
Trade-offs and Operational Limits
Healthchecks improve startup coordination, but they are not free. Every check consumes CPU, memory, and I/O inside the container. A check that runs every second and executes an expensive query can create unnecessary load, especially when you run many replicas. Keep checks cheap and pick intervals that match the service’s startup and recovery behavior.
Compose dependency conditions also have a scope limit. They control startup and creation order in the Compose workflow. They do not continuously enforce dependency health across the full lifetime of the system. If Redis becomes unhealthy after the API is already running, Compose does not automatically stop or restart the API because of that dependency condition. That is why application-level timeout, retry, and circuit breaking behavior still matters.
Another limitation is portability of assumptions. A healthcheck that works well in local Compose may not be the right probe for a production orchestrator. In Kubernetes, liveness probes should not fail because a downstream dependency is unavailable, or the orchestrator may restart healthy application pods during an incident. Readiness probes can represent dependency availability, but you need to decide whether you want to remove pods from traffic or keep them serving partial functionality. Compose gives you fewer probe types, so be explicit about what your health endpoint means.
There is also a debugging cost when healthchecks are poorly designed. A check that depends on external systems can make a service flap between healthy and unhealthy for reasons outside its control. A check that is too shallow can report healthy while the application cannot serve real requests. The practical balance is to make the healthcheck represent the minimum capability required for the next dependent service or traffic source to use it safely.
Used with care, healthchecks and depends_on conditions make Compose startup behavior predictable. They turn an implicit timing assumption into an explicit contract: the database accepts connections, the cache responds to ping, the migration completed, and the API serves its health endpoint. That contract is easier to observe, easier to debug, and much safer to run in automated environments where timing is never guaranteed.