Docker › Compose

Controlling Docker Compose startup order with healthchecks

Fix Spring Boot Connection refused errors on startup using Docker Compose healthchecks, service_healthy conditions, and one-shot Flyway migrations.

Controlling Docker Compose startup order with healthchecks

Adding depends_on in Docker Compose does not stop Spring Boot from crashing with Connection refused while PostgreSQL is still initializing. This post explains the gap between container startup and service readiness, and shows how to chain PostgreSQL, Redis, one-shot Flyway migrations, and Spring Boot using native Compose v2 healthchecks.

Tested with Docker Engine 27, Docker Compose v2, PostgreSQL 17, Redis 7, Flyway 10, and Spring Boot 3.4.


Why Spring Boot crashes even with depends_on

Almost everyone who containerizes a Spring Boot app for local integration tests or CI hits this failure at least once. You declare the dependency explicitly in compose.yaml:

1
2
3
4
5
6
7
8
9
services:
  postgres:
    image: postgres:17-alpine
    # ... omitted ...

  app:
    build: .
    depends_on:
      - postgres

You run docker compose up -d, and a few seconds later app exits with status 1. Checking docker compose logs app shows the familiar HikariCP stack trace:

1
2
3
4
5
6
7
org.postgresql.util.PSQLException: Connection to postgres:5432 refused.
Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
	at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:342)
	at com.zaxxer.hikari.pool.HikariPool.checkException(HikariPool.java:448)
	at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:464)
...
Caused by: java.net.ConnectException: Connection refused

The reason is straightforward: Docker’s idea of “started” is not the same as your database being “ready.”

sequenceDiagram
    autonumber
    actor Dev as Dev / CI
    participant Compose as Docker Compose
    participant DB as PostgreSQL
    participant App as Spring Boot
    Dev->>Compose: docker compose up
    Compose->>DB: Start container (Created -> Running)
    Note over Compose: Default depends_on satisfied immediately
    Compose->>App: Start Spring Boot container
    Note over DB: Running initdb and WAL recovery (port closed)
    App->>DB: HikariCP connects to TCP 5432
    DB-->>App: Connection refused (TCP RST)
    Note over App: Startup fails (Exit 1)
    Note over DB: Ready to accept connections (too late)

Container started vs. service ready

When you write depends_on: [postgres] without a condition, Compose defaults to condition: service_started. The moment the Docker daemon forks the container’s PID 1 and transitions the container state from Created to Running, Compose treats the dependency as met and launches app.

A database container still has real work to do after PID 1 starts:

  1. Validate environment variables and data directory permissions.
  2. Run initdb on an empty volume or replay WAL (Write-Ahead Log) segments on an existing one.
  3. Spawn background writer, autovacuum, and checkpointer processes.
  4. Bind the TCP socket on port 5432 and log database system is ready to accept connections.

That sequence takes 1–2 seconds on a warm volume and 5–10+ seconds on a fresh initialization. Meanwhile, Spring Boot initializes DataSource and HikariCP immediately, hits a closed socket, receives a kernel TCP RST, and terminates.

Avoid legacy wait-script hacks: In the Compose v1 era, teams commonly baked wait-for-it.sh, dockerize, or nc -z loops into their application ENTRYPOINT. That bloats your app image with extra networking tools, breaks on minimal/distroless images, and mixes infrastructure orchestration into application packaging.

Compose v2 solves this natively with healthcheck and depends_on.<service>.condition, requiring zero changes to your application Dockerfile.


Writing healthchecks for PostgreSQL and Redis

A healthcheck block tells Docker how to probe whether a container is genuinely ready to serve traffic rather than merely alive.

PostgreSQL with pg_isready

The official PostgreSQL image bundles pg_isready, a lightweight utility that verifies the server is accepting connections without running heavy queries:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
services:
  postgres:
    image: postgres:17-alpine
    container_name: app-postgres
    environment:
      POSTGRES_DB: myapp
      POSTGRES_USER: myuser
      POSTGRES_PASSWORD: mysecretpassword
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U myuser -d myapp"]
      interval: 3s
      timeout: 3s
      retries: 5
      start_period: 5s

How each parameter behaves:

  • test: Command executed inside the container. Exit code 0 means healthy; non-zero means unhealthy.
  • interval: How often Docker runs the probe. The default is 30s, which wastes time locally—3s to 5s gives fast feedback.
  • timeout: Max time a single probe may run before counting as a failure.
  • retries: Consecutive failures required to mark the container unhealthy.
  • start_period: Grace period during initial boot. Probes that fail during start_period don’t increment the failure counter, while a passing probe immediately marks the container healthy.

CMD vs. CMD-SHELL: Use ["CMD", "redis-cli", "ping"] when you want to execute a binary directly without a shell. Use ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"] whenever you need shell variable expansion, pipes (|), or && chaining. Remember to escape container-side environment variables with $$ so Compose doesn’t interpolate them from the host.

Redis with redis-cli ping

Redis images ship with redis-cli, making the readiness probe a one-liner:

1
2
3
4
5
6
7
8
9
10
11
12
services:
  redis:
    image: redis:7-alpine
    container_name: app-redis
    ports:
      - "6379:6379"
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 3s
      timeout: 2s
      retries: 3
      start_period: 2s

When Redis is ready, redis-cli ping returns PONG with exit code 0. If you configure --requirepass, switch to ["CMD-SHELL", "redis-cli -a $$REDIS_PASSWORD ping | grep PONG"] as shown in my local Spring Boot Compose setup.


Gating startup with condition: service_healthy

Once both dependencies expose healthchecks, switch depends_on on the Spring Boot service to the long syntax with condition: service_healthy:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: spring-app
    ports:
      - "8080:8080"
    environment:
      SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/myapp
      SPRING_DATASOURCE_USERNAME: myuser
      SPRING_DATASOURCE_PASSWORD: mysecretpassword
      SPRING_DATA_REDIS_HOST: redis
      SPRING_DATA_REDIS_PORT: 6379
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy
flowchart TD
    subgraph Infra["Infrastructure Services"]
        P["postgres (starting)"] -->|"pg_isready = 0"| PH["postgres (healthy)"]
        R["redis (starting)"] -->|"redis-cli ping = 0"| RH["redis (healthy)"]
    end
    subgraph Gate["Compose Dependency Gate"]
        PH --> Check{"All service_healthy met?"}
        RH --> Check
    end
    subgraph AppBoot["Application Startup"]
        Check -->|"Yes"| App["Start spring-app"]
        App --> Hikari["HikariCP pool ready"]
        App --> Lettuce["Redis client ready"]
    end

Running docker compose up now holds spring-app until both probes pass:

1
2
3
4
5
[+] Running 3/3
 ✔ Container app-postgres  Healthy                                        4.2s
 ✔ Container app-redis     Healthy                                        1.8s
 ✔ Container spring-app    Created                                        0.0s
Attaching to spring-app

Because spring-app only starts after both containers report Healthy, HikariCP connects cleanly on the first attempt.


Chaining one-shot Flyway migrations

In real services, the database being online isn’t enough—schema migrations often need to finish before any application instance boots.

Running Flyway inside Spring Boot works for a single local instance, but it introduces two headaches as your setup grows:

  • Multiple app replicas starting at once race to acquire the flyway_schema_history lock.
  • A broken migration leaves the Spring Boot container crashing in a restart loop, obscuring the actual SQL error behind framework logs.

Instead, you can run the official flyway/flyway image as a one-shot job (restart: "no") and gate spring-app on condition: service_completed_successfully, which waits for exit code 0.

flowchart TD
    DB["1. postgres<br/>(service_healthy)"] -->|"Accepting connections"| M["2. flyway<br/>(One-shot DDL migration)"]
    M -->|"Exit code 0<br/>(service_completed_successfully)"| A["3. spring-app<br/>(Application boot)"]

Full compose.yaml with Flyway chaining

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
services:
  postgres:
    image: postgres:17-alpine
    container_name: app-postgres
    restart: unless-stopped
    environment:
      POSTGRES_DB: myapp
      POSTGRES_USER: myuser
      POSTGRES_PASSWORD: mysecretpassword
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U myuser -d myapp"]
      interval: 3s
      timeout: 3s
      retries: 5
      start_period: 5s

  redis:
    image: redis:7-alpine
    container_name: app-redis
    restart: unless-stopped
    ports:
      - "6379:6379"
    volumes:
      - redis_data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 3s
      timeout: 2s
      retries: 3
      start_period: 2s

  flyway:
    image: flyway/flyway:10-alpine
    container_name: app-flyway-migration
    restart: "no" # One-shot migration job; do not restart on exit
    command: -connectRetries=10 migrate
    volumes:
      - ./src/main/resources/db/migration:/flyway/sql:ro
    environment:
      FLYWAY_URL: jdbc:postgresql://postgres:5432/myapp
      FLYWAY_USER: myuser
      FLYWAY_PASSWORD: mysecretpassword
    depends_on:
      postgres:
        condition: service_healthy

  app:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: spring-app
    restart: unless-stopped
    ports:
      - "8080:8080"
    environment:
      SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/myapp
      SPRING_DATASOURCE_USERNAME: myuser
      SPRING_DATASOURCE_PASSWORD: mysecretpassword
      SPRING_DATA_REDIS_HOST: redis
      SPRING_DATA_REDIS_PORT: 6379
      # Disable in-app Flyway because the dedicated container handles migrations
      SPRING_FLYWAY_ENABLED: "false"
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy
      flyway:
        condition: service_completed_successfully

volumes:
  postgres_data:
  redis_data:

When you run docker compose up, the startup sequence executes deterministically:

  1. postgres and redis start in parallel.
  2. Both pass their healthchecks within 2–4 seconds and transition to Healthy.
  3. flyway starts, applies pending SQL migrations, and exits with code 0.
  4. Compose sees flyway exit cleanly and starts spring-app, which connects to an up-to-date schema with zero connection errors.

Caveats, trade-offs, and checklist

Comparing depends_on conditions

ConditionWaits forBest used for
service_started (default)Container PID 1 runningLightweight sidecars with no readiness requirement
service_healthyhealthcheck passing (exit 0)Databases, caches, message brokers, APIs
service_completed_successfullyContainer exiting with code 0Flyway/Liquibase migrations, one-shot seed jobs

When not to rely solely on depends_on

depends_on only governs initial container startup order. It does not protect your application if PostgreSQL restarts mid-flight or experiences a brief network blip after spring-app is already running. In production (and Kubernetes, where pods start concurrently anyway), your application still needs connection pool retries, reasonable timeouts, and Spring Boot Actuator health probes.

Watch out for CI hangs and missing start_period: If a large database volume needs 15 seconds to replay WAL on boot and you omit start_period, Docker can mark the container unhealthy prematurely and abort docker compose up. Conversely, cap retries × (interval + timeout) to roughly 30–60 seconds so broken CI runs fail fast instead of burning runner minutes.

Startup orchestration checklist

  • Replace shorthand depends_on: [postgres] with condition: service_healthy for every stateful dependency.
  • Set start_period on database healthchecks so cold initialization doesn’t trip retries.
  • Use restart: "no" and condition: service_completed_successfully for one-shot Flyway/Liquibase containers, and set SPRING_FLYWAY_ENABLED: "false" on the app container.
  • Keep compose.yaml as the filename (Compose Specification standard) and run docker compose up -d --wait in CI scripts so the CLI blocks until all healthchecks pass.
This post is licensed under CC BY 4.0 by the author.