Docker › Container

Monitoring Spring Boot containers with Docker HEALTHCHECK

Detect hung Spring Boot containers using Actuator liveness probes, Docker HEALTHCHECK, and an autoheal sidecar that restarts unhealthy services.

Monitoring Spring Boot containers with Docker HEALTHCHECK

A Spring Boot container can show Up in docker ps while timing out every single HTTP request. Here is how to catch zombie containers with Spring Boot Actuator liveness probes, Docker HEALTHCHECK, and an autoheal sidecar that restarts unhealthy services automatically.


The zombie container problem

One of the hardest production failures to catch is a service that hasn’t crashed, yet can’t serve traffic.

Under traffic spikes or slow downstream calls, JVM services often end up stuck in one of these states:

  • HikariCP connection pool exhaustion: Slow queries or leaked connections leave zero idle connections, blocking every database-backed request.
  • Tomcat worker thread starvation: Synchronous I/O pins all threads up to max-threads, so new TCP requests queue and time out.
  • Thread deadlocks or continuous Full GC: Lock contention freezes worker threads, or a nearly full heap triggers back-to-back Stop-The-World pauses until the app stops responding.
flowchart TD
    Client["Client / API Gateway"] -->|"HTTP GET /api/v1/orders"| DockerHost["Docker Host (Port 8080)"]
    DockerHost --> Container["Container (PID 1: java -jar)"]
    subgraph InsideContainer["Inside Container"]
        JVM["JVM Process (Alive)"]
        Pool["HikariCP / Thread Pool (Exhausted)"]
        JVM --- Pool
    end
    Container -.->|"Hang / Timeout"| DockerHost
    DockerHost --x|"504 Gateway Timeout"| Client
    DockerDaemon["Docker Daemon"] -.->|"Checks PID 1 only"| Container
    DockerDaemon --> Status["docker ps: Up 5 hours (False healthy)"]
    style Status fill:#f8d7da,stroke:#dc3545,stroke-width:2px
    style Pool fill:#fff3cd,stroke:#ffc107,stroke-width:2px

By default, the Docker daemon only checks whether PID 1 is still alive. Even when every Tomcat thread is stuck and users are getting 504 Gateway Timeout, java -jar hasn’t exited, so docker ps happily reports Up 5 hours. Load balancers keep routing requests to the dead instance and spread the failure upstream.


How Docker HEALTHCHECK and its four flags work

Docker’s HEALTHCHECK instruction lets you run an in-container probe from a Dockerfile or compose.yaml to verify that the application is actually working, not just running.

Healthcheck state machine

Once a healthcheck is defined, Docker tracks three states beyond Up:

stateDiagram-v2
    [*] --> STARTING: Container starts
    STARTING --> HEALTHY: First probe passes
    STARTING --> UNHEALTHY: Fails N retries after start-period
    HEALTHY --> UNHEALTHY: Fails N consecutive probes
    UNHEALTHY --> HEALTHY: Recovers on a single passing probe

Tuning the four flags

FlagDefaultRecommendedRole and tuning notes
--interval30s10s - 15sHow often Docker runs the probe. Too short adds load; too long delays failure detection.
--timeout30s3s - 5sMax wait per probe. A healthy liveness endpoint responds in milliseconds, so keep this under 5 seconds.
--start-period0s30s - 60sCritical for JVM apps. Grace period during boot where failed probes don’t count toward retries.
--retries33Consecutive failures required to mark the container unhealthy. Prevents flapping during brief GC pauses.

Never omit --start-period for Spring Boot: Component scanning, connection pool initialization, and bean wiring take tens of seconds. With the default 0s grace period, probes fail immediately during startup and can mark a healthy container unhealthy before it finishes booting, trapping it in a restart loop.

Dockerfile syntax

1
2
3
# Dockerfile
HEALTHCHECK --interval=10s --timeout=3s --start-period=45s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:8080/actuator/health/liveness || exit 1

Docker interprets the probe command’s exit code as:

  • 0: healthy
  • 1: unhealthy
  • 2: reserved (do not use)

Choosing a probe tool in slim images: Production images based on Alpine or Distroless rarely include curl. On Alpine, wget --spider (which checks the HTTP status without downloading the body) is built in. On Distroless images with no shell or HTTP client, you’ll need a tiny static binary or a Java-based probe.


Wiring Spring Boot Actuator liveness and readiness probes

Pointing HEALTHCHECK at / or a business endpoint is a bad idea, and pointing it at the default /actuator/health endpoint can trigger an even worse cascading outage.

Why /actuator/health is the wrong target for restarts

By default, Spring Boot Actuator’s /actuator/health aggregates every external dependency: PostgreSQL, Redis, RabbitMQ, disk space, and more.

Suppose PostgreSQL drops off the network for ten seconds. /actuator/health immediately returns 503 DOWN. If Docker’s HEALTHCHECK watches that aggregate endpoint and triggers a restart:

  1. The database blips, so Docker restarts your Spring Boot container.
  2. The container boots while the database is still down and enters a crash loop.
  3. When the database comes back, every container boots at once and hammers it with a connection storm.

Restarting a healthy app container because an external dependency is down only makes the outage worse.

Separating Liveness from Readiness

Since Spring Boot 2.3, Actuator splits container health into two Kubernetes-style probes:

flowchart TD
    DockerHC["Docker HEALTHCHECK"] -->|"Restart decision"| Liveness["/actuator/health/liveness"]
    Proxy["Nginx / Load Balancer"] -->|"Traffic routing"| Readiness["/actuator/health/readiness"]
    Liveness --> L1["JVM integrity and internal deadlocks"]
    Readiness --> R1["DB pool, cache, and broker availability"]
    style Liveness fill:#d1ecf1,stroke:#0c5460,stroke-width:2px
    style Readiness fill:#d4edda,stroke:#155724,stroke-width:2px
  • Liveness (/actuator/health/liveness): Is the internal app state still valid? If it’s broken, restart the container.
  • Readiness (/actuator/health/readiness): Can this instance accept traffic right now? If a dependency is slow or unreachable, stop routing traffic to it—don’t restart it.

When not to use Actuator liveness alone: If your app suffers from a silent thread-pool deadlock where the embedded server can still answer /actuator/health/liveness on a separate management port, a simple liveness probe won’t catch it unless it runs on the same server port or includes a lightweight internal check.

Spring Boot configuration (application.yaml)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
management:
  endpoints:
    web:
      exposure:
        include: health, info
  endpoint:
    health:
      # Expose /actuator/health/liveness and /actuator/health/readiness
      probes:
        enabled: true
      show-details: always
  health:
    livenessstate:
      enabled: true
    readinessstate:
      enabled: true

Once enabled, verify the liveness endpoint directly:

1
2
$ curl -s http://localhost:8080/actuator/health/liveness
{"status":"UP"}

Closing the restart gap with autoheal

There is one major Docker quirk that catches almost everyone the first time they configure HEALTHCHECK:

Docker does not restart unhealthy containers on its own. Settings like restart: unless-stopped or restart: always only fire when the PID 1 process exits. If the process is still running while marked unhealthy, the Docker daemon leaves it alone.

On Kubernetes or Docker Swarm, the orchestrator replaces unhealthy containers automatically. On a single Docker host or Compose stack, you can add the lightweight willfarrell/autoheal sidecar to watch Docker events and restart flagged containers.

flowchart TD
    App["Spring Boot Container (app)"] -->|"wget liveness probe"| HC["Docker HEALTHCHECK"]
    HC -->|"3 consecutive failures"| Status["State: unhealthy"]
    Status -.-> Socket["/var/run/docker.sock"]
    Autoheal["Autoheal Sidecar"] -->|"Watch health events"| Socket
    Autoheal -->|"Trigger restart"| Restart["docker restart app"]
    Restart --> App
    style Autoheal fill:#e2e3e5,stroke:#383d41,stroke-width:2px
    style Restart fill:#f8d7da,stroke:#dc3545,stroke-width:2px

Complete compose.yaml setup

Here is a complete stack wiring Spring Boot, PostgreSQL, and autoheal together:

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
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: order-service
    ports:
      - "8080:8080"
    environment:
      SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/orderdb
      SPRING_DATASOURCE_USERNAME: orderuser
      SPRING_DATASOURCE_PASSWORD: orderpassword
    labels:
      # Opt this container into autoheal monitoring
      autoheal: "true"
    healthcheck:
      test: ["CMD-SHELL", "wget --no-verbose --tries=1 --spider http://localhost:8080/actuator/health/liveness || exit 1"]
      interval: 10s
      timeout: 3s
      start_period: 40s
      retries: 3
    depends_on:
      db:
        condition: service_healthy
    restart: unless-stopped

  db:
    image: postgres:17-alpine
    container_name: order-db
    environment:
      POSTGRES_DB: orderdb
      POSTGRES_USER: orderuser
      POSTGRES_PASSWORD: orderpassword
    volumes:
      - db_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U orderuser -d orderdb"]
      interval: 5s
      timeout: 3s
      start_period: 10s
      retries: 5
    restart: unless-stopped

  autoheal:
    image: willfarrell/autoheal:latest
    container_name: autoheal-daemon
    environment:
      # Only watch containers labeled autoheal=true
      AUTOHEAL_CONTAINER_LABEL: "autoheal"
      AUTOHEAL_INTERVAL: "5"
      AUTOHEAL_START_PERIOD: "30"
    volumes:
      # Mount the host Docker socket so autoheal can call restart
      - /var/run/docker.sock:/var/run/docker.sock
    restart: always

volumes:
  db_data:

Three details make this configuration work cleanly:

  1. Startup ordering (condition: service_healthy): Spring Boot waits until pg_isready passes instead of racing PostgreSQL during boot.
  2. Label opt-in (autoheal: "true"): autoheal only restarts containers you explicitly label, leaving infrastructure containers untouched.
  3. Socket access: Mounting /var/run/docker.sock gives autoheal permission to issue docker restart. Treat that container as privileged and lock down its image tag in production.

Injecting a failure and verifying recovery

To verify the full loop, I added a temporary debug endpoint that flips Spring Boot’s internal liveness state to BROKEN.

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
package com.example.demo.controller;

import org.springframework.boot.availability.AvailabilityChangeEvent;
import org.springframework.boot.availability.LivenessState;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/internal/test")
public class HealthTestController {

    private final ApplicationEventPublisher eventPublisher;

    public HealthTestController(ApplicationEventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
    }

    /**
     * Force the application liveness state to BROKEN for testing.
     */
    @PostMapping("/break-liveness")
    public String breakLiveness() {
        AvailabilityChangeEvent.publish(eventPublisher, this, LivenessState.BROKEN);
        return "Liveness state changed to BROKEN";
    }
}

Start the stack and trigger the endpoint:

1
2
3
4
5
6
7
8
9
10
11
12
13
# 1. Start the Compose stack
$ docker compose up -d

# 2. Confirm all containers report healthy
$ docker ps --format "table {{.Names}}\t{{.Status}}"
NAMES               STATUS
autoheal-daemon     Up 20 seconds
order-service       Up 20 seconds (healthy)
order-db            Up 20 seconds (healthy)

# 3. Inject a liveness failure
$ curl -X POST http://localhost:8080/internal/test/break-liveness
Liveness state changed to BROKEN

Right away, the liveness endpoint starts returning 503 Service Unavailable:

1
2
3
4
$ curl -i http://localhost:8080/actuator/health/liveness
HTTP/1.1 503 Service Unavailable
Content-Type: application/vnd.spring-boot.actuator.v3+json
{"status":"DOWN"}

After three failed probes (about 30 seconds at a 10-second interval), docker ps flips to (unhealthy):

1
2
3
$ docker ps --format "table {{.Names}}\t{{.Status}}"
NAMES               STATUS
order-service       Up About a minute (unhealthy)

Seconds later, autoheal-daemon logs the event and restarts order-service:

1
2
3
4
2026-06-14 12:05:12 Monitoring containers...
2026-06-14 12:05:17 Container order-service (d9f1a23e5bc8) found to be 'unhealthy'
2026-06-14 12:05:17 Restarting container order-service (d9f1a23e5bc8)...
2026-06-14 12:05:22 Container order-service restarted successfully!

The restarted container enters (health: starting) during start_period and returns to (healthy) on its own—no manual SSH or 3 a.m. restart needed.

Inspecting failed healthcheck output: To see the exact stdout, stderr, and exit codes from the last five healthcheck runs, inspect .State.Health directly:

docker inspect --format='{{json .State.Health}}' order-service | jq

This tells you immediately whether the probe timed out, got a 503, or failed because wget wasn’t installed.


Healthcheck design checklist

Keep these four rules in mind when wiring container healthchecks:

  1. Keep probes cheap: Never run heavy SQL queries or outbound HTTP calls inside a healthcheck—otherwise the probe itself becomes a load generator.
  2. Never mix liveness and readiness: Bind Docker HEALTHCHECK to /actuator/health/liveness (internal process health), and reserve /actuator/health/readiness for load-balancer routing.
  3. Give JVM apps a generous start_period: Production nodes often boot slower than your laptop. Set start_period high enough (30–60 seconds) to avoid boot-time restart loops.
  4. Remove debug endpoints before shipping: Delete or profile-gate test endpoints like /internal/test/break-liveness so they never reach production.
This post is licensed under CC BY 4.0 by the author.