Skip to lesson

Health checks and start-up order

ShopLite's API starts in a few seconds, but MySQL needs 10 to 30 seconds on a fresh volume. If the API connects too early it crashes. A health check makes the API wait until the database is truly ready.

The problem: depends_on does not wait for readiness

Running vs ready is the gap between a process that exists and one that can answer requests. A MySQL container is running at once but ready only after several seconds.

Compose can start db before api with depends_on, yet the API still crashed at start-up. The snippet below shows the short form; the Java model after it shows the race.

YAML
services:  db:    image: mysql:8.4  api:    build: .    depends_on:      - db          # starts db first, but does NOT wait for MySQL to be ready

Example 1 · The race: the app connects before MySQL is ready

StartupRaceDemo.javaJava
public class StartupRaceDemo {    static final int MYSQL_READY_AT = 14;   // seconds after up, fresh volume
    static void tryConnect(String who, int second) {        String result = second >= MYSQL_READY_AT ? "connected" : "Connection refused -> exit 1";        System.out.printf("t=%2ds %-26s %s%n", second, who, result);    }
    public static void main(String[] args) {        System.out.println("depends_on: [db]  (start order only)");        tryConnect("api starts, Flyway connects", 4);
        System.out.println("depends_on: condition: service_healthy");        int second = 0;        while (second < MYSQL_READY_AT) {            second += 5;                       // healthcheck interval 5s        }        System.out.printf("t=%2ds db reported healthy%n", second);        tryConnect("api starts, Flyway connects", second + 4);    }}
Output
depends_on: [db]  (start order only)
t= 4s api starts, Flyway connects Connection refused -> exit 1
depends_on: condition: service_healthy
t=15s db reported healthy
t=19s api starts, Flyway connects connected

What this code does

  • With start order only, the API starts right after the MySQL container exists and connects at second 4, long before MySQL is ready at second 14.
  • With a health condition, Compose waits for the first passing check (second 15 with a 5-second interval), so the API always finds a ready database. The numbers are a simplified model; real times depend on your machine.

depends_on tells Compose the order in which to start services: db is started before api. In its short form that is all it does; Compose does not wait until MySQL can answer queries.

On a fresh volume MySQL first creates its system tables, the shoplite database and the user, which can take 10 to 30 seconds. Spring Boot starts in a few seconds, Flyway asks for a connection, gets Connection refused and the app exits. Run up again and it may work. A bug that appears only sometimes is called a race condition: the result depends on which side wins the race.

healthcheck for MySQL

A healthcheck is a command Docker runs inside the container again and again. Exit code 0 means healthy; any other code means unhealthy.

The container's status then shows (health: starting), (healthy) or (unhealthy). For MySQL the usual command is mysqladmin ping, pointed at 127.0.0.1.

Example 2 · compose.yaml: MySQL healthcheck and a healthy start

Runs in: the shoplite-api project folder with Docker 27+

YAML
name: shopliteservices:  db:    image: mysql:8.4    environment:      MYSQL_ROOT_PASSWORD: rootpass      MYSQL_DATABASE: shoplite      MYSQL_USER: shoplite      MYSQL_PASSWORD: shoplitepass    volumes:      - mysql-data:/var/lib/mysql    healthcheck:      test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -u root -p$$MYSQL_ROOT_PASSWORD --silent"]      interval: 10s      timeout: 5s      retries: 10      start_period: 30s  api:    build: .    ports:      - "8080:8080"    environment:      DB_URL: jdbc:mysql://db:3306/shoplite      DB_USER: shoplite      DB_PASSWORD: shoplitepass    depends_on:      db:        condition: service_healthyvolumes:  mysql-data:
Sample output
$ docker compose up -d
[+] Running 4/4
 ✔ Network shoplite_default      Created    0.1s
 ✔ Volume "shoplite_mysql-data"  Created    0.0s
 ✔ Container shoplite-db-1       Healthy   21.7s
 ✔ Container shoplite-api-1      Started   21.9s

$ docker compose ps --format "table {{.Service}}\t{{.Status}}"
SERVICE   STATUS
api       Up 6 seconds
db        Up 28 seconds (healthy)

What this code does

  • The password variable is written with two dollar signs so Compose passes a literal dollar sign to the shell inside the container, which then reads the container's own variable. With one dollar sign, Compose would try to fill it in from your computer.
  • The up output shows Healthy for db after about 22 seconds, and only then Started for api. CMD-SHELL runs the command through sh, which is needed for the variable.

mysqladmin ping exits with 0 as soon as the server answers, even if the login fails, so the password in the command is optional. Use 127.0.0.1: during the first start the image runs a temporary server that accepts only local socket connections, and a ping over the socket could pass too early.

Four settings control the check:

  • interval: time between checks (10s).
  • timeout: how long one check may take before it counts as failed (5s).
  • retries: failures in a row before the status becomes unhealthy (10).
  • start_period: a warm-up time whose failures do not count (30s).

Predict the output

What does the status say?

The db container starts at second 0. MySQL is ready at second 14.

Round 1 of 2

Checks run at 10 s, 20 s, 30 s. At second 12, what does docker compose ps show for db?

healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1"]
interval: 10s
timeout: 5s
retries: 3
start_period: 30s

depends_on with condition: service_healthy

service_healthy is a depends_on condition. Compose starts the dependent service only after the other service reports healthy; if it never does, up stops with an error.

Add condition: service_healthy to the API's depends_on, and Compose holds the API back until MySQL's healthcheck passes. The snippet below is the long form.

YAML
  api:    build: .    depends_on:      db:        condition: service_healthy   # wait for the healthcheck to pass        restart: true                # restart api if db is restarted by Compose
Two timelines. With plain depends_on, db and api start together, MySQL is ready only at about 15 seconds, and the api tries to connect at 6 seconds and crashes. With condition service_healthy the api waits until the healthcheck passes at about 20 seconds, then starts and connects.
Plain depends_on versus service_healthy

The other conditions are service_started (the short form's behaviour) and service_completed_successfully, for one-off jobs such as a migration container that must finish with exit code 0 first.

Find the bug

Find the line that does not wait

The API still starts before MySQL is ready. Tap the wrong line.

The db service has a healthcheck, but the API still crashes at start-up.

Round 1 of 2

A health endpoint for the app

A health endpoint is a URL that answers 200 when the app can do its job and an error such as 503 (Service Unavailable) when it cannot.

ShopLite already has /actuator/health from the Spring Boot section. The small Java server below shows the idea without Spring: it answers DOWN until a warm-up finishes, then UP.

Example 3 · A /health endpoint that turns UP after warm-up

HealthServerDemo.javaJava
import com.sun.net.httpserver.HttpServer;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.util.concurrent.atomic.AtomicBoolean;
public class HealthServerDemo {    static final AtomicBoolean ready = new AtomicBoolean(false);
    public static void main(String[] args) throws Exception {        // In a container, bind to 0.0.0.0 and port 8080; here: localhost and any free port        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/health", exchange -> {            boolean up = ready.get();            byte[] body = (up ? "{\"status\":\"UP\"}" : "{\"status\":\"DOWN\"}")                    .getBytes(StandardCharsets.UTF_8);            exchange.getResponseHeaders().set("Content-Type", "application/json");            exchange.sendResponseHeaders(up ? 200 : 503, body.length);            try (OutputStream out = exchange.getResponseBody()) {                out.write(body);            }        });        server.start();        URI health = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/health");
        HttpClient client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();        for (int check = 1; check <= 4; check++) {            if (check == 3) {                warmUp();            }            HttpResponse<String> response = client.send(                    HttpRequest.newBuilder(health).build(), HttpResponse.BodyHandlers.ofString());            String verdict = response.statusCode() == 200 ? "healthy" : "not yet";            System.out.println("check " + check + ": " + response.statusCode() + " "                    + response.body() + " -> " + verdict);        }        server.stop(0);    }
    static void warmUp() throws InterruptedException {        Thread.sleep(200);              // pretend: pool filled, caches loaded        ready.set(true);        System.out.println("warm-up finished");    }}
Output
check 1: 503 {"status":"DOWN"} -> not yet
check 2: 503 {"status":"DOWN"} -> not yet
warm-up finished
check 3: 200 {"status":"UP"} -> healthy
check 4: 200 {"status":"UP"} -> healthy

What this code does

  • The handler answers 503 with DOWN until ready is true, then 200 with UP. A healthcheck tool such as wget or curl --fail exits non-zero on 503, so Docker counts those checks as failures.
  • The loop plays the role of Docker calling the check repeatedly. Spring Boot's /actuator/health works the same way and also includes the database in its answer.

Example 4 · API healthcheck in compose.yaml

Runs in: the shoplite-api project folder with Docker 27+

YAML
  api:    build: .    ports:      - "8080:8080"    depends_on:      db:        condition: service_healthy    healthcheck:      # needs wget in the image; with curl use: curl --fail --silent http://localhost:8080/actuator/health      test: ["CMD-SHELL", "wget -qO- http://localhost:8080/actuator/health || exit 1"]      interval: 10s      timeout: 3s      retries: 5      start_period: 40s
Sample output
$ docker compose ps --format "table {{.Service}}\t{{.Status}}"
SERVICE   STATUS
api       Up 52 seconds (healthy)
db        Up 75 seconds (healthy)

$ docker inspect --format "{{json .State.Health.Status}}" shoplite-api-1
"healthy"

What this code does

  • Inside the API container localhost:8080 is correct, because the check runs in the same container as the app. start_period: 40s gives Spring Boot and Flyway time to start without counting failures.
  • With a healthy API, docker compose up --wait can wait for the whole stack and scripts or CI can run tests right after it.

The Compose healthcheck for the API calls that URL with a tool that exists in the image, such as wget or curl. Check first: many slim images ship neither. Run docker compose exec api sh -c "command -v curl wget", and if both are missing, install one in the Dockerfile's runtime stage or leave the API without a healthcheck.

Still retry: Hikari and restart: on-failure

Back-off means waiting longer after each failed retry, for example 100 ms, then 200 ms, then 400 ms, so a service that is still recovering is not hammered with attempts.

Health checks fix start-up order, but the database can still disappear later: a restart, a network blip, an upgrade. A robust app expects that and retries.

Example 5 · Retrying the first connection with back-off

ConnectRetryDemo.javaJava
public class ConnectRetryDemo {    static int attempts = 0;
    // Pretend database: refuses the first 3 attempts, then accepts    static void connect() {        attempts++;        if (attempts <= 3) {            throw new IllegalStateException("Connection refused");        }    }
    public static void main(String[] args) throws InterruptedException {        long waitMs = 100;        for (int attempt = 1; attempt <= 6; attempt++) {            try {                connect();                System.out.println("attempt " + attempt + ": connected");                return;            } catch (IllegalStateException e) {                System.out.println("attempt " + attempt + ": " + e.getMessage()                        + ", retry in " + waitMs + " ms");                Thread.sleep(waitMs);                waitMs *= 2;                   // back-off: wait longer each time            }        }        System.out.println("giving up: exit 1, restart: on-failure starts a new container");    }}
Output
attempt 1: Connection refused, retry in 100 ms
attempt 2: Connection refused, retry in 200 ms
attempt 3: Connection refused, retry in 400 ms
attempt 4: connected

What this code does

  • Each failure is logged and followed by a longer wait (100, 200, 400 ms). This back-off stops a crowd of apps from hammering a database that is still starting.
  • Hikari's initialization-fail-timeout gives Spring Boot the same behaviour for the first connection; after the limit, the app exits and restart: on-failure is the last safety net.

Two settings back up the health check:

  • Retry on start: spring.datasource.hikari.initialization-fail-timeout: 60000 makes the Hikari pool keep trying to get its first connection for up to 60 seconds instead of failing on the first refusal.
  • Restart on crash: restart: on-failure makes Docker start the container again when it exits with a non-zero code.

Together they give layers of safety: wait for healthy, retry for a while, and if all else fails, restart.

Fix the error

Make the API patient

The API gives up too early. Pick the replacement for the highlighted line.

Round 1 of 2

Hikari should keep trying the first connection for up to 60 seconds.

spring:
datasource:
hikari:
initialization-fail-timeout: 1

Error

HikariPool-1 - Exception during pool initialization.
Caused by: java.net.ConnectException: Connection refused
Retrying hides nothing important: each failed attempt is still logged, so you can see a slow or broken database in the logs.

Next step

Check your understanding

12 quick questions