TExcelTAD
Home › Docker Swarm › Healthchecks & Self-Healing

Healthchecks & Self-Healing

Swarm replaces a task when its container exits. But many failures don't end the process: the app deadlocks, loses its database connection, or answers every request with an error while the process happily stays alive. A healthcheck gives Swarm a way to see those failures. With one, an unhealthy container is treated like a crashed one: the task fails and a new task replaces it. Healthchecks also make startup and rolling updates safer, because a task only counts as running once it is healthy.

Defining a healthcheck

The check is the same one Docker uses on a single host (see HEALTHCHECK and LABEL and Compose healthchecks). It can come from three places, the later ones overriding the earlier:

  1. the image's HEALTHCHECK instruction;
  2. the stack file's healthcheck: key;
  3. docker service create/update flags: --health-cmd, --health-interval, --health-timeout, --health-retries, --health-start-period, --health-start-interval, or --no-healthcheck.
compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  api:
    image: ghcr.io/acme/shop-api:2.5.0
    healthcheck:
      test: curl -fsS http://localhost:8000/health || exit 1
      interval: 10s
      timeout: 2s
      retries: 3
      start_period: 30s
      start_interval: 2s
    deploy:
      replicas: 3
  worker:
    image: ghcr.io/acme/shop-worker:2.5.0
    healthcheck:
      disable: true
version: "3.13"
services:
  api:
    deploy:
      replicas: 3
    healthcheck:
      test:
        - CMD-SHELL
        - curl -fsS http://localhost:8000/health || exit 1
      timeout: 2s
      interval: 10s
      retries: 3
      start_period: 30s
      start_interval: 2s
    image: ghcr.io/acme/shop-api:2.5.0
  worker:
    healthcheck:
      disable: true
    image: ghcr.io/acme/shop-worker:2.5.0

A string test became CMD-SHELL (run through /bin/sh -c), and disable: true switches off a check inherited from the image. The stack format is strict about types: durations must be strings with a unit.

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  api:
    image: ghcr.io/acme/shop-api:2.5.0
    healthcheck:
      test: ["CMD", "/app/healthcheck"]
      interval: 10
services.api.healthcheck.interval: must be a string

What Swarm does with the health status

Health status Effect in Swarm
starting (inside start_period) the task stays in STARTING; it is not counted as running yet and receives no traffic through the service's virtual IP
healthy the task becomes RUNNING; it is added to the load balancer
unhealthy (retries failures in a row) the task fails ("container unhealthy"); its container is stopped, it leaves the load balancer, and the restart policy creates a replacement

So, unlike plain docker run (where an unhealthy container just carries a label and keeps running), Swarm acts on the result. That is the self-healing loop.

A timeline

The model follows one slot of a service: the first container needs about 25 seconds to warm up; later it gets stuck. Probes run every interval; during start_period they run every start_interval, and failures in that period do not count:

python · try it yourself
interval, start_interval, start_period, retries, restart_delay = 10, 2, 30, 3, 5

def probe(container, t):
    age = t - container["started"]
    if age < container["warmup"]:
        return False                          # still loading
    return not (container["stuck_at"] is not None and age >= container["stuck_at"])

def run_slot(containers, until):
    t, gen = 0, 0
    c = dict(containers[0], started=0)
    status, fails, state = "starting", 0, "STARTING"
    print(f"t={t:>3}s api.1 (task {gen + 1}) STARTING")
    while t < until:
        age = t - c["started"]
        step = start_interval if status == "starting" and age < start_period else interval
        t += step
        ok = probe(c, t)
        if ok:
            fails = 0
            if status != "healthy":
                status, state = "healthy", "RUNNING"
                print(f"t={t:>3}s probe ok -> healthy: task RUNNING, added to the VIP")
        else:
            in_grace = status == "starting" and t - c["started"] <= start_period
            if not in_grace:
                fails += 1
                print(f"t={t:>3}s probe failed ({fails}/{retries})")
            if fails >= retries:
                print(f"t={t:>3}s unhealthy -> task FAILED, removed from the VIP, container stopped")
                gen += 1
                t += restart_delay
                c = dict(containers[min(gen, len(containers) - 1)], started=t)
                status, fails = "starting", 0
                print(f"t={t:>3}s api.1 (task {gen + 1}) STARTING (restart delay {restart_delay}s)")

run_slot([{"warmup": 25, "stuck_at": 60}, {"warmup": 25, "stuck_at": None}], until=150)
t=  0s api.1 (task 1) STARTING
t= 26s probe ok -> healthy: task RUNNING, added to the VIP
t= 66s probe failed (1/3)
t= 76s probe failed (2/3)
t= 86s probe failed (3/3)
t= 86s unhealthy -> task FAILED, removed from the VIP, container stopped
t= 91s api.1 (task 2) STARTING (restart delay 5s)
t=117s probe ok -> healthy: task RUNNING, added to the VIP

Three things to notice: the warm-up failures inside the start period did not count; the stuck container was replaced after three failed probes, about 30 seconds after it got stuck; and the replacement took the same slot (api.1) as a new task.

Choosing the settings

  • interval × retries is how long a broken task may keep receiving traffic. 10s × 3 = up to about 30 seconds. Lower it for latency-sensitive services; don't go so low that a short pause (a garbage collection, a slow disk) kills healthy tasks.
  • timeout must be shorter than the interval and long enough for the check under load.
  • start_period must cover the slowest realistic start (migrations, cache warm-up, JIT). Too short and tasks are killed while starting, which looks like a crash loop. start_interval (Docker 25+) lets the check run often during this period so a fast start is detected quickly.
  • What to check: that this process can serve requests. Avoid checking dependencies (the database, other services): if the database blips, every replica would become unhealthy at once and Swarm would restart all of them, which doesn't fix the database and makes recovery slower.
  • The check runs inside the container, so the tool it calls (curl, wget, a small binary) must exist in the image. Minimal images often ship a dedicated health binary or use the app itself (["CMD", "/app/server", "healthcheck"]).

Healthchecks and updates

During a rolling update, Swarm waits for each new task to become RUNNING (that is, healthy if it has a check) before continuing, and then keeps watching it for the monitor period. A new version that never becomes healthy is therefore detected and can trigger an automatic rollback. Without a healthcheck, "the process started" is all Swarm knows, and a broken release looks fine. Rolling Updates goes through it step by step.

No startup ordering

On a single host, Compose can wait for a dependency to be healthy (depends_on with condition: service_healthy; see Startup Order). Swarm has no startup ordering at all: docker stack deploy creates all services at once, and the stack format only accepts the short list form of depends_on, which Swarm then ignores:

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  db:
    image: postgres:17
  api:
    image: ghcr.io/acme/shop-api:2.5.0
    depends_on:
      db:
        condition: service_healthy
services.api.depends_on: must be a list

In a cluster, services must cope with dependencies that are not there yet or disappear for a while: retry connections with backoff at startup, and let the healthcheck plus restart policy handle the rest. A service that exits because the database isn't ready is simply restarted after the restart delay until it is.

Learn more: Rolling Updates · Kubernetes probes · Troubleshooting

Test yourself

A Swarm task's container becomes unhealthy. What happens?

  1. It keeps running with an 'unhealthy' label, like with docker run
  2. The task fails, the container is stopped and a new task replaces it
  3. The node is drained
  4. Swarm restarts the process inside the same container

Does a task in its start period, before its first successful healthcheck, receive traffic through the service's VIP?

  1. Yes, as soon as the container starts
  2. No, it is still STARTING and is added once it is healthy
  3. Only from the routing mesh
  4. Only if it is on a manager

Why should a healthcheck usually not test the database the service depends on?

  1. Healthchecks cannot open network connections
  2. A database outage would mark every replica unhealthy and Swarm would restart them all, which doesn't help
  3. It is slower
  4. Swarm forbids it