| |

Docker 42 🐳 Service Dependencies and Startup Ordering: depends_on with Healthcheck Conditions

⏱️ Estimated read: 18 min | |

A multi-container application has an order. The database must be ready before the API can connect. The API must be ready before the frontend can proxy to it. The migration must complete before the application starts serving traffic. Compose’s depends_on is the key that expresses this order, and the key has two forms with very different semantics. The short form waits for the container to start. The long form waits for a condition to be satisfied — a healthcheck to pass, or a container to exit successfully. The difference between “the container is running” and “the service is ready” is the difference between a stack that works and a stack that crashes on startup.

The short form is the trap. depends_on: [db] starts the db container before the api container, but it does not wait for PostgreSQL to finish its initialization. The db container’s status is Up as soon as the process starts, and the api container starts immediately after. If the API tries to connect within the first second, PostgreSQL may still be replaying its WAL or running its initialization scripts, and the connection is refused. The API crashes, the restart policy restarts it, and the cycle repeats until PostgreSQL is finally ready. This is the startup race condition, and it is the most common Compose problem.

The long form solves it. depends_on: { db: { condition: service_healthy } } makes Compose wait for the db healthcheck to pass before starting the api container. The healthcheck is defined on the db service, and it runs a command that verifies the database is accepting connections. When the healthcheck passes, Compose starts the api. The API’s first connection attempt succeeds, and the stack starts cleanly. The long form requires the db service to have a healthcheck; without one, the service_healthy condition cannot be satisfied.

This chapter covers three areas. First, why startup ordering matters — the startup race condition and the difference between started and ready. Second, the two forms of depends_on — the short form, the long form, and the three conditions (service_started, service_healthy, service_completed_successfully). Third, the patterns for healthchecks and initialization — the healthcheck definitions for PostgreSQL, MySQL, Redis, and HTTP services, and the init-container pattern for one-time setup. The chapter ends with a complete example session, a quick reference, best practices, common pitfalls, real-world examples, and diagrams showing the startup sequence.

Key point: The short form of depends_on waits only for the container to start. The long form waits for a condition: service_started, service_healthy, or service_completed_successfully. Use service_healthy for services that need their dependencies to be ready, and service_completed_successfully for one-time initialization. The dependency must have a healthcheck for service_healthy to work.


Why startup ordering matters

The startup race condition. A container’s status is Up when its main process starts. But the process may not be ready to serve requests. PostgreSQL starts its process immediately, but it takes time to initialize the data directory, replay the write-ahead log, and start accepting connections. A Node.js API starts its process immediately, but it takes time to load its modules, connect to the database, and start listening. If the API starts before PostgreSQL is ready, the first connection fails. The API may crash, or it may retry. If it crashes, the restart policy restarts it, and the cycle continues until PostgreSQL is ready. The stack eventually works, but the logs are full of errors, and the startup time is longer than necessary.

The readiness problem. “Started” and “ready” are different states. A container is started when its process is running. A service is ready when it can accept requests. The gap between the two is the initialization time, and it varies by service. PostgreSQL may take a few seconds. A Java application may take thirty seconds. A machine-learning model may take minutes to load. The depends_on short form ignores the gap. The long form with service_healthy waits for the gap to close.

The one-time-initialization problem. Some services need to run once and exit: a database migration, a seed script, a certificate generation. The service should complete before the application starts. The service_completed_successfully condition waits for the container to exit with code 0. If the container exits with a non-zero code, the dependent service does not start, and the stack fails. This is the init-container pattern, and it is the correct way to run one-time setup in Compose.

The healthcheck problem. The service_healthy condition requires the dependency to have a healthcheck. The healthcheck is a command that Docker runs periodically inside the container. The exit code determines the health status: 0 is healthy, 1 is unhealthy, 2 is reserved. The start_period gives the service time to initialize before the failures count. The interval, timeout, and retries control the check frequency and the failure threshold. A well-designed healthcheck verifies that the service is actually ready, not just that the process is running.

The circular-dependency problem. A circular dependency is a cycle in the depends_on graph. Service A depends on B, and B depends on A. Compose cannot resolve the order, and it reports an error. The fix is to break the cycle by removing one of the dependencies or by introducing a third service. A common case is a frontend and an API that both depend on each other for readiness; the frontend should depend on the API, and the API should not depend on the frontend.

The trade-off. The service_healthy condition adds a dependency on the healthcheck. If the healthcheck is slow or misconfigured, the startup is delayed or the stack fails. The start_period must be long enough for the service to initialize, but not so long that a genuine failure is hidden. The healthcheck command must be available in the container; a minimal image may not have curl or pg_isready. The trade-off is between the reliability of the ordered startup and the complexity of the healthcheck configuration.


a. The short form and the long form

The depends_on key has two forms. The short form is a list of service names, and it waits only for the containers to start.

services:
  api:
    depends_on:
      - db
      - cache

The api service starts after the db and cache containers have started. But the api does not wait for db to be ready or for cache to be ready. If the API tries to connect before PostgreSQL is ready, the connection fails.

The long form is a map, and each service has a condition. The conditions are service_started, service_healthy, and service_completed_successfully.

services:
  api:
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_started
      migrate:
        condition: service_completed_successfully

The api service starts after the db healthcheck passes, the cache container starts, and the migrate container exits with code 0. The three conditions can be combined, and each one has its own semantics.

service_started is the equivalent of the short form. It waits for the container to start. It is the default when the condition is omitted.

service_healthy waits for the healthcheck to pass. The dependency must have a healthcheck, and the healthcheck must define the test, interval, timeout, retries, and optionally start_period. When the healthcheck passes, the condition is satisfied.

service_completed_successfully waits for the container to exit with code 0. It is used for one-time initialization: a migration, a seed, a build step. If the container exits with a non-zero code, the condition fails, and the dependent service does not start.


b. Healthchecks for common services

The service_healthy condition depends on the healthcheck. The healthcheck must verify that the service is ready, not just that the process is running.

PostgreSQL. The pg_isready command checks whether the server is accepting connections. It is included in the official PostgreSQL image.

services:
  db:
    image: postgres:16-alpine
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
      interval: 5s
      timeout: 5s
      retries: 5
      start_period: 10s

The -U and -d flags specify the user and the database. The start_period gives PostgreSQL time to initialize the data directory before the failures count.

MySQL. The mysqladmin ping command checks whether the server is accepting connections.

services:
  db:
    image: mysql:8
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${MYSQL_ROOT_PASSWORD}"]
      interval: 5s
      timeout: 5s
      retries: 5
      start_period: 30s

The -h localhost flag makes the check connect over TCP rather than the Unix socket. The -p flag specifies the password. The start_period is longer for MySQL, because its initialization takes longer.

Redis. The redis-cli ping command returns PONG when the server is ready.

services:
  cache:
    image: redis:7-alpine
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5

HTTP services. An HTTP service can use wget or curl to check an endpoint. The --spider flag makes wget send a HEAD request and exit with the status code.

services:
  api:
    image: myapi
    healthcheck:
      test: ["CMD", "wget", "--spider", "-q", "http://localhost:3000/health"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 20s

The /health endpoint should verify the critical dependencies: the database connection, the cache connection, and any other service the API needs. A healthcheck that only verifies the process is listening is not sufficient.

A minimal image without a healthcheck tool. A scratch or distroless image may not have curl, wget, or a shell. In that case, the healthcheck can use a built-in command or a small binary that is included in the image.

services:
  api:
    image: myapi-distroless
    healthcheck:
      test: ["CMD", "/app/healthcheck"]
      interval: 10s
      timeout: 5s
      retries: 5

The /app/healthcheck binary is a small program that checks the service and exits with the appropriate code.


c. The init-container pattern

The service_completed_successfully condition implements the init-container pattern. A service runs once, performs its task, and exits. The dependent services start after the exit.

services:
  migrate:
    image: myapi
    command: ["npm", "run", "migrate"]
    depends_on:
      db:
        condition: service_healthy
    environment:
      DATABASE_URL: postgres://app:${DB_PASSWORD}@db:5432/appdb

  api:
    image: myapi
    command: ["npm", "start"]
    depends_on:
      migrate:
        condition: service_completed_successfully
      db:
        condition: service_healthy
    environment:
      DATABASE_URL: postgres://app:${DB_PASSWORD}@db:5432/appdb

The migrate service runs the database migration. It waits for the db healthcheck to pass, runs the migration, and exits with code 0. The api service waits for the migration to complete successfully and for the db healthcheck to pass, and then it starts. The migration runs exactly once, and the API starts with the schema in place.

The migrate service does not have a restart policy, because it is meant to run once. The api service has the restart policy. The migrate service’s logs show the migration output, and the api service’s logs show the application output.

The init-container pattern is also used for seeding data, generating certificates, and warming caches. The pattern is the same: a one-time service with service_completed_successfully, and the dependent services wait for it.


Complete Example Session

# ============================================
# PART 1: THE SHORT FORM (THE TRAP)
# ============================================

services:
  api:
    image: myapi
    depends_on:
      - db

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_PASSWORD: secret

# The api starts after the db container starts.
# The api does NOT wait for PostgreSQL to be ready.
# The first connection may fail.


# ============================================
# PART 2: THE LONG FORM WITH service_healthy
# ============================================

services:
  api:
    image: myapi
    depends_on:
      db:
        condition: service_healthy

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_PASSWORD: secret
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 5s
      retries: 5
      start_period: 10s

# The api starts after the db healthcheck passes.
# The api's first connection succeeds.


# ============================================
# PART 3: THE THREE CONDITIONS
# ============================================

services:
  api:
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_started
      migrate:
        condition: service_completed_successfully

# db: waits for the healthcheck to pass
# cache: waits for the container to start
# migrate: waits for the container to exit with code 0


# ============================================
# PART 4: POSTGRESQL HEALTHCHECK
# ============================================

services:
  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      POSTGRES_DB: appdb
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d appdb"]
      interval: 5s
      timeout: 5s
      retries: 5
      start_period: 10s


# ============================================
# PART 5: MYSQL HEALTHCHECK
# ============================================

services:
  db:
    image: mysql:8
    environment:
      MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
      MYSQL_DATABASE: appdb
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${DB_PASSWORD}"]
      interval: 5s
      timeout: 5s
      retries: 5
      start_period: 30s


# ============================================
# PART 6: REDIS HEALTHCHECK
# ============================================

services:
  cache:
    image: redis:7-alpine
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5


# ============================================
# PART 7: HTTP HEALTHCHECK
# ============================================

services:
  api:
    image: myapi
    healthcheck:
      test: ["CMD", "wget", "--spider", "-q", "http://localhost:3000/health"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 20s


# ============================================
# PART 8: THE INIT-CONTAINER PATTERN
# ============================================

services:
  migrate:
    image: myapi
    command: ["npm", "run", "migrate"]
    depends_on:
      db:
        condition: service_healthy
    environment:
      DATABASE_URL: postgres://app:${DB_PASSWORD}@db:5432/appdb

  api:
    image: myapi
    command: ["npm", "start"]
    depends_on:
      migrate:
        condition: service_completed_successfully
      db:
        condition: service_healthy
    environment:
      DATABASE_URL: postgres://app:${DB_PASSWORD}@db:5432/appdb


# ============================================
# PART 9: THE COMPLETE STACK
# ============================================

name: fullstack

services:
  web:
    image: nginx:alpine
    ports:
      - "80:80"
    depends_on:
      api:
        condition: service_healthy
    networks:
      - frontend

  migrate:
    build: ./api
    command: ["npm", "run", "migrate"]
    depends_on:
      db:
        condition: service_healthy
    environment:
      DATABASE_URL: postgres://app:${DB_PASSWORD}@db:5432/appdb
    networks:
      - backend

  api:
    build: ./api
    command: ["npm", "start"]
    depends_on:
      migrate:
        condition: service_completed_successfully
      db:
        condition: service_healthy
      cache:
        condition: service_started
    environment:
      DATABASE_URL: postgres://app:${DB_PASSWORD}@db:5432/appdb
      REDIS_URL: redis://cache:6379
    healthcheck:
      test: ["CMD", "wget", "--spider", "-q", "http://localhost:3000/health"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 20s
    networks:
      - frontend
      - backend

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      POSTGRES_DB: appdb
    volumes:
      - db-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d appdb"]
      interval: 5s
      timeout: 5s
      retries: 5
      start_period: 10s
    networks:
      - backend

  cache:
    image: redis:7-alpine
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5
    networks:
      - backend

volumes:
  db-data:

networks:
  frontend:
  backend:
    internal: true


# ============================================
# PART 10: THE STARTUP SEQUENCE
# ============================================

# $ docker compose up -d
# [+] Running 6/6
#  ✔ Container fullstack-db-1       Healthy
#  ✔ Container fullstack-cache-1    Started
#  ✔ Container fullstack-migrate-1  Exited (0)
#  ✔ Container fullstack-api-1      Healthy
#  ✔ Container fullstack-web-1      Started
#
# The order:
#   db starts → healthcheck passes
#   cache starts
#   migrate starts (db is healthy) → exits 0
#   api starts (migrate completed, db healthy, cache started)
#   api healthcheck passes
#   web starts (api is healthy)

The ten parts show the short form, the long form, the three conditions, the PostgreSQL healthcheck, the MySQL healthcheck, the Redis healthcheck, the HTTP healthcheck, the init-container pattern, the complete stack, and the startup sequence.


Quick Reference

The Two Forms

FormWaits for
depends_on: [db]Container started
depends_on: { db: { condition: ... } }The condition

The Three Conditions

ConditionWaits for
service_startedContainer started
service_healthyHealthcheck passes
service_completed_successfullyExit code 0

Healthcheck Keys

KeyDefaultPurpose
test—The command to run
interval30sTime between checks
timeout30sMax time for one check
retries3Failures before unhealthy
start_period0sGrace period

Common Healthchecks

ServiceCommand
PostgreSQLpg_isready -U user -d db
MySQLmysqladmin ping -h localhost
Redisredis-cli ping
HTTPwget --spider -q http://localhost/health

The Startup Order

OrderServiceWaits for
1db—
2cache—
3migratedb healthy
4apimigrate completed, db healthy, cache started
5webapi healthy

Best Practices

✅ Do This:

# Use service_healthy for readiness
depends_on:
  db:
    condition: service_healthy                                            # ✅
# Define a healthcheck on the dependency
healthcheck:
  test: ["CMD-SHELL", "pg_isready -U app"]                                # ✅
# Set a start_period for slow-booting services
healthcheck:
  start_period: 30s                                                        # ✅
# Use service_completed_successfully for migrations
depends_on:
  migrate:
    condition: service_completed_successfully                              # ✅
# Use a health endpoint that checks dependencies
healthcheck:
  test: ["CMD", "wget", "--spider", "-q", "http://localhost:3000/health"]  # ✅

❌ Don’t Do This:

# Don't use the short form for readiness
depends_on:
  - db  # does not wait for readiness                                      # ❌
# Don't use service_healthy without a healthcheck
depends_on:
  db:
    condition: service_healthy  # db has no healthcheck                    # ❌
# Don't set start_period too short
start_period: 1s  # PostgreSQL needs more                                  # ❌
# Don't use a healthcheck that only checks the process
test: ["CMD", "true"]  # always passes                                     # ❌
# Don't create circular dependencies
# api depends on web, web depends on api                                   # ❌

Common Pitfalls

PitfallWhy It HappensFix
API crashes on startupShort form of depends_onUse service_healthy
service_healthy never satisfiedNo healthcheck on the dependencyAdd a healthcheck
Healthcheck always failsWrong command or missing toolCheck the command in the container
Startup takes too longstart_period too longReduce the grace period
Genuine failure hiddenstart_period too longUse a shorter grace period
Migration runs twiceNo service_completed_successfullyUse the condition
Circular dependency errorA depends on B, B depends on ABreak the cycle

Real-World Examples

1. Short Form

depends_on:
  - db

2. service_healthy

depends_on:
  db:
    condition: service_healthy

3. service_completed_successfully

depends_on:
  migrate:
    condition: service_completed_successfully

4. PostgreSQL Healthcheck

healthcheck:
  test: ["CMD-SHELL", "pg_isready -U app"]
  interval: 5s
  retries: 5
  start_period: 10s

5. MySQL Healthcheck

healthcheck:
  test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
  start_period: 30s

6. Redis Healthcheck

healthcheck:
  test: ["CMD", "redis-cli", "ping"]

7. HTTP Healthcheck

healthcheck:
  test: ["CMD", "wget", "--spider", "-q", "http://localhost:3000/health"]

8. Init Container

migrate:
  command: ["npm", "run", "migrate"]
  depends_on:
    db:
      condition: service_healthy

9. Multiple Conditions

depends_on:
  db:
    condition: service_healthy
  cache:
    condition: service_started

10. Complete Stack

api:
  depends_on:
    migrate:
      condition: service_completed_successfully
    db:
      condition: service_healthy

Visual

The Startup Race Condition

┌──────────────────────────────────────────────────────────────┐
│  THE STARTUP RACE CONDITION                                  │
│                                                              │
│  WITHOUT service_healthy:                                    │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  t=0s   db container starts                          │    │
│  │  t=0s   api container starts                         │    │
│  │  t=1s   api connects to db → REFUSED                 │    │
│  │  t=1s   api crashes                                  │    │
│  │  t=2s   api restarts (restart policy)                │    │
│  │  t=3s   api connects → REFUSED                       │    │
│  │  t=5s   db is ready                                  │    │
│  │  t=6s   api connects → SUCCESS                       │    │
│  │                                                       │    │
│  │  The stack works, but the logs are full of errors.   │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  WITH service_healthy:                                       │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  t=0s   db container starts                          │    │
│  │  t=5s   db healthcheck passes                        │    │
│  │  t=5s   api container starts                         │    │
│  │  t=6s   api connects → SUCCESS                       │    │
│  │                                                       │    │
│  │  The stack starts cleanly.                           │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
└──────────────────────────────────────────────────────────────┘

The Three Conditions

┌──────────────────────────────────────────────────────────────┐
│  THE THREE CONDITIONS                                        │
│                                                              │
│  service_started:                                            │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  Waits for the container to start.                   │    │
│  │  Does NOT wait for readiness.                        │    │
│  │  Equivalent to the short form.                       │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  service_healthy:                                            │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  Waits for the healthcheck to pass.                  │    │
│  │  The dependency must have a healthcheck.             │    │
│  │  Use for services that need their dependencies ready.│    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  service_completed_successfully:                             │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  Waits for the container to exit with code 0.        │    │
│  │  Use for one-time initialization.                    │    │
│  │  If the exit code is non-zero, the condition fails.  │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
└──────────────────────────────────────────────────────────────┘

The Init-Container Pattern

┌──────────────────────────────────────────────────────────────┐
│  THE INIT-CONTAINER PATTERN                                  │
│                                                              │
│  ┌──────────────┐                                            │
│  │  db          │                                            │
│  │  postgres    │                                            │
│  │              │                                            │
│  │  healthcheck │                                            │
│  └──────────────┘                                            │
│         │                                                    │
│         │ healthy                                            │
│         ▼                                                    │
│  ┌──────────────┐                                            │
│  │  migrate     │                                            │
│  │  npm run     │                                            │
│  │  migrate     │                                            │
│  │              │                                            │
│  │  exits 0     │                                            │
│  └──────────────┘                                            │
│         │                                                    │
│         │ completed successfully                             │
│         ▼                                                    │
│  ┌──────────────┐                                            │
│  │  api         │                                            │
│  │  npm start   │                                            │
│  │              │                                            │
│  │  healthcheck │                                            │
│  └──────────────┘                                            │
│         │                                                    │
│         │ healthy                                            │
│         ▼                                                    │
│  ┌──────────────┐                                            │
│  │  web         │                                            │
│  │  nginx       │                                            │
│  └──────────────┘                                            │
│                                                              │
│  The migration runs once, and the API starts with the        │
│  schema in place.                                            │
│                                                              │
└──────────────────────────────────────────────────────────────┘

The Complete Startup Sequence

┌──────────────────────────────────────────────────────────────┐
│  THE COMPLETE STARTUP SEQUENCE                               │
│                                                              │
│  Time ──────────────────────────────────────────────►        │
│                                                              │
│  db:      [start]──[init]──[healthcheck passes]──[healthy]   │
│                                                              │
│  cache:   [start]──[ready]                                   │
│                                                              │
│  migrate:                      [start]──[migrate]──[exit 0]  │
│                                                              │
│  api:                                                 [start]│
│                                                    [health]  │
│                                                              │
│  web:                                                        │
│                                                      [start] │
│                                                              │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  1. db starts, healthcheck passes                    │    │
│  │  2. cache starts                                     │    │
│  │  3. migrate starts (db healthy), exits 0             │    │
│  │  4. api starts (migrate completed, db healthy)       │    │
│  │  5. api healthcheck passes                           │    │
│  │  6. web starts (api healthy)                         │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Summary

ItemValue
Short formdepends_on: [db]; waits for start
Long formdepends_on: { db: { condition: ... } }
service_startedContainer started
service_healthyHealthcheck passes
service_completed_successfullyExit code 0
Healthcheck testThe command to run
start_periodGrace period for initialization
Init containerOne-time service with service_completed_successfully
Circular dependencyA cycle in the depends_on graph
Startup raceThe API starts before the DB is ready

Key takeaways:

  • The short form of depends_on waits only for the container to start. It does not wait for the service to be ready. The dependent service may try to connect before the dependency is accepting connections, and the connection fails.
  • The long form waits for a condition. The service_started condition is the same as the short form. The service_healthy condition waits for the healthcheck to pass. The service_completed_successfully condition waits for the container to exit with code 0.
  • The service_healthy condition requires a healthcheck. The dependency must define a healthcheck with a test command. Without one, the condition cannot be satisfied, and the dependent service never starts.
  • The healthcheck must verify readiness, not just liveness. A healthcheck that only checks whether the process is running passes before the service is ready. The healthcheck should verify the critical dependencies: the database connection, the cache connection, and any other service the application needs.
  • The start_period gives the service time to initialize. During the start period, failures do not count toward the retry limit. The period must be long enough for the service to initialize, but not so long that a genuine failure is hidden.
  • The service_completed_successfully condition implements the init-container pattern. A one-time service runs a migration, a seed, or a build, and the dependent services start after it exits with code 0. If the exit code is non-zero, the dependent services do not start.
  • A circular dependency is an error. The depends_on graph must be a directed acyclic graph. A cycle cannot be resolved, and Compose reports an error. The fix is to break the cycle by removing one of the dependencies or introducing a third service.
  • The startup order is the dependency graph’s topological order. Compose starts the services in the order that satisfies all the conditions. The services with no dependencies start first, and the services with dependencies start after their conditions are satisfied.

Remember: The depends_on key controls the startup order, and the two forms have different semantics. The short form waits only for the container to start. The long form waits for a condition: service_started, service_healthy, or service_completed_successfully. The service_healthy condition is the correct choice for services that need their dependencies to be ready, and it requires the dependency to have a healthcheck. The service_completed_successfully condition is the correct choice for one-time initialization. The startup race condition is the most common Compose problem, and the long form with service_healthy is the fix. The healthcheck must verify readiness, not just liveness, and the start_period must be tuned for the service’s initialization time. The result is a stack that starts cleanly, with no errors in the logs and no restart loops.


Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!