Docker Health Check Configuration for Container Reliability
Configure Docker HEALTHCHECK with curl, wget, or custom scripts so Docker can detect containers that stop responding — not just ones that crash.
Overview
Your container can show Up 3 hours in docker ps and still be useless. The process is alive, but the app inside is deadlocked, out of memory, or stuck on a dead connection — and every request times out. Docker alone can’t tell the difference, because “container is up” only means the main process exists.
That’s the gap HEALTHCHECK fills: it tells Docker to test the application, not just the process. On a schedule, Docker runs a command inside the container and reports starting, healthy, or unhealthy — visible in docker ps and docker inspect.
One thing to know upfront: plain docker run doesn’t restart unhealthy containers. The status is informational unless something acts on it — Docker Swarm replaces unhealthy tasks, Compose stacks pair it with restart policies or an autoheal sidecar, and Kubernetes ignores HEALTHCHECK entirely in favor of its own probe system (covered in the health check pattern). If you need the /health endpoint itself, implement the health check endpoint first.
When to Use
- You run containers in production and need the platform to detect app-level failures, not just process crashes
- You use Docker Swarm and want unhealthy tasks replaced automatically
- You want
docker psto show health status for manual or scripted checks - Your app can be running but not responding (deadlocks, memory exhaustion, stuck connections)
- You use Compose and want
depends_on: condition: service_healthyfor startup ordering
When Not to Use
- On Kubernetes-managed pods — Kubernetes ignores
HEALTHCHECK; define liveness, readiness, and startup probes in the pod spec instead - For one-shot or batch containers — there’s no long-running process to probe
- When the only consumer of health data is an external load balancer — point the LB at your health endpoint directly instead of duplicating checks
Solution
The pattern is always the same: a cheap command that exits 0 when the app is fine and exits non-zero when it isn’t. Whatever you pick, make it something already baked into the image.
Basic HEALTHCHECK with curl
FROM node:20-alpine
WORKDIR /app
COPY . .
RUN npm ci --omit=dev
HEALTHCHECK --interval=30s --timeout=5s --retries=3 --start-period=10s \
CMD curl -f http://localhost:3000/health || exit 1
EXPOSE 3000
CMD ["node", "server.js"]
HEALTHCHECK with wget (Alpine images without curl)
FROM node:20-alpine
WORKDIR /app
COPY . .
RUN npm ci --omit=dev
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1
EXPOSE 3000
CMD ["node", "server.js"]
HEALTHCHECK with custom script
FROM python:3.12-slim
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -r requirements.txt
COPY healthcheck.sh /healthcheck.sh
RUN chmod +x /healthcheck.sh
HEALTHCHECK --interval=30s --timeout=10s --retries=3 --start-period=15s \
CMD /healthcheck.sh
EXPOSE 8000
CMD ["gunicorn", "app:app", "--bind", "0.0.0.0:8000"]
#!/bin/bash
# healthcheck.sh
set -e
# Check if the HTTP endpoint responds
response=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8000/health)
if [ "$response" = "200" ]; then
exit 0
else
echo "Health check failed: HTTP $response"
exit 1
fi
HEALTHCHECK for PostgreSQL
FROM postgres:16-alpine
HEALTHCHECK --interval=10s --timeout=5s --retries=5 \
CMD pg_isready -U postgres -d mydb || exit 1
HEALTHCHECK for Redis
FROM redis:7-alpine
HEALTHCHECK --interval=10s --timeout=3s --retries=3 \
CMD redis-cli ping | grep PONG || exit 1
Docker Compose healthcheck with depends_on
# docker-compose.yml
services:
api:
build: .
ports:
- "3000:3000"
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
worker:
build: ./worker
depends_on:
api:
condition: service_healthy
redis:
condition: service_healthy
redis:
image: redis:7-alpine
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 3s
retries: 3
Health endpoint in Node.js
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/health" && req.method === "GET") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ status: "healthy" }));
return;
}
// ... other routes
});
server.listen(3000);
Health endpoint in Python (FastAPI)
from fastapi import FastAPI
app = FastAPI()
@app.get("/health")
async def health():
return {"status": "healthy"}
Explanation
Options
Five flags control when and how Docker runs the probe:
--interval: How often the check runs (default 30s). Go shorter only for services where seconds matter.--timeout: How long a check may take before it counts as failed (default 30s).--retries: How many failures in a row flip the container to unhealthy (default 3).--start-period: Warm-up window at boot where failures don’t count yet (default 0s).--start-interval: Interval between checks during the start period (default 5s, requires Docker 25.0+). Lets a fast-booting app reachhealthysooner instead of waiting a full--intervalper probe.
The probe runs inside the container itself: exit 0 marks it healthy, exit 1 marks it unhealthy. Any other exit code counts as a failure too, so || exit 1 guards against commands that return 2 or die with a signal.
Health states
- starting: The warm-up window while
start-periodruns — failures during it are ignored. - healthy: The last check exited 0.
- unhealthy: The check failed
retriestimes in a row once the start period ended.
What “unhealthy” actually does
In plain Docker, unhealthy is only a flag. docker ps shows it, and docker inspect exposes the last probe results under .State.Health — but nothing is restarted by itself. restart: always reacts to the container exiting, not to its health status. Automatic replacement comes from Docker Swarm (which reschedules unhealthy tasks), Kubernetes probes, or a watcher like willfarrell/autoheal that restarts unhealthy containers for you. See the Dockerfile HEALTHCHECK reference for the full option list.
depends_on and service_healthy
In Compose, depends_on with condition: service_healthy holds a service’s startup until the dependency passes its health check — the standard fix for “the API crashed because Postgres wasn’t ready yet”. Note that it’s a startup gate only: if the dependency goes unhealthy later, Compose won’t restart the dependent. Per-environment tuning of these values is a good fit for Compose override files, as shown in the advanced examples below. Details in the Compose file reference.
Debugging a stuck check
When a container flaps between starting and unhealthy, look at the last probe results before touching anything else:
docker inspect --format='{{json .State.Health}}' <container-name> | jq
The output shows the last five checks with exit code, stdout, and stderr — the classic cause is curl or wget missing from the image, which fails with exit 127 before your app is ever tested.
Variants
Each probe method trades image size for flexibility. Pick the simplest one that works with what’s already installed:
| Check Method | Image Requirement | Use When |
|---|---|---|
| curl -f | curl installed | Standard HTTP check |
| wget —spider | wget installed | Alpine without curl |
| Custom script | bash + tools | Multi-step checks |
| pg_isready | PostgreSQL image | Database readiness |
| redis-cli ping | Redis image | Cache readiness |
| node -e | Node.js image | JS-based check |
For HTTP services, prefer curl or wget over a custom script — fewer moving parts. Reach for a script only when the check genuinely needs two or more steps.
Advanced Examples
The setup above covers the everyday cases. These variants handle the situations that show up once the check runs in production: compiled runtimes, multi-signal checks, audit logging, per-environment tuning, and services without an HTTP listener. Every file on this page is also in the companion repo, ready to run.
Health Endpoint in Java (Spring Boot)
// src/main/java/com/example/HealthController.java
package com.example;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@RestController
public class HealthController {
@GetMapping("/health")
public String health() {
return "{\"status\":\"healthy\"}";
}
}
@Component
public class DatabaseHealthIndicator implements HealthIndicator {
@Override
public Health health() {
// Check database connectivity
try {
// Perform a simple query
return Health.up().withDetail("database", "reachable").build();
} catch (Exception e) {
return Health.down().withDetail("error", e.getMessage()).build();
}
}
}
# application.yml — Enable actuator health endpoints
management:
endpoints:
web:
exposure:
include: health,info
endpoint:
health:
show-details: when_authorized
For custom indicators that plug into these health groups — database queries, Redis pings, external API probes — see Custom Health Checks with Spring Boot Actuator.
Multi-Step Health Check Script
#!/bin/bash
# healthcheck-advanced.sh — Multi-step health verification
set -e
FAIL=0
# Step 1: Check HTTP endpoint
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8000/health 2>/dev/null || echo "000")
if [ "$HTTP_CODE" != "200" ]; then
echo "FAIL: HTTP endpoint returned $HTTP_CODE"
FAIL=1
fi
# Step 2: Check disk space
DISK_USAGE=$(df / | awk 'NR==2 {print int($5)}')
if [ "$DISK_USAGE" -gt 90 ]; then
echo "FAIL: Disk usage at ${DISK_USAGE}%"
FAIL=1
fi
# Step 3: Check if critical process is running
if ! pgrep -x "gunicorn" > /dev/null; then
echo "FAIL: gunicorn process not found"
FAIL=1
fi
# Step 4: Check memory usage
MEM_USAGE=$(free | awk '/Mem:/ {printf "%.0f", $3/$2 * 100}')
if [ "$MEM_USAGE" -gt 95 ]; then
echo "FAIL: Memory usage at ${MEM_USAGE}%"
FAIL=1
fi
if [ "$FAIL" -eq 0 ]; then
exit 0
else
exit 1
fi
Health Check with Logging
#!/bin/bash
# healthcheck-logged.sh — Health check with audit log
LOG_FILE="/var/log/healthcheck.log"
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3000/health 2>/dev/null || echo "000")
if [ "$HTTP_CODE" = "200" ]; then
echo "$TIMESTAMP OK HTTP=$HTTP_CODE" >> "$LOG_FILE"
exit 0
else
echo "$TIMESTAMP FAIL HTTP=$HTTP_CODE" >> "$LOG_FILE"
exit 1
fi
Docker Compose Override for Health Check Tuning
# docker-compose.prod.yml — Override health check for production
services:
api:
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 15s
timeout: 3s
retries: 5
start_period: 30s
db:
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d mydb && psql -U postgres -d mydb -c 'SELECT 1'"]
interval: 10s
timeout: 5s
retries: 10
start_period: 60s
# Apply production health check overrides
docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
Health Check for Message Queue Worker
A worker without an HTTP server can’t answer a probe request, so the usual trick is a heartbeat file the worker touches on every loop iteration. The health check then measures the file’s age instead of hitting an endpoint:
FROM node:20-alpine
WORKDIR /app
COPY . .
RUN npm ci --omit=dev
# Health check for a worker that processes queue messages
HEALTHCHECK --interval=60s --timeout=10s --retries=3 --start-period=30s \
CMD node -e " \
const fs = require('fs'); \
const stats = fs.statSync('/tmp/worker.heartbeat'); \
const age = (Date.now() - stats.mtimeMs) / 1000; \
if (age > 120) { console.error('Heartbeat stale: ' + age + 's'); process.exit(1); } \
console.log('Heartbeat OK: ' + age + 's'); \
"
CMD ["node", "worker.js"]
// worker.js — Write heartbeat file periodically
const fs = require("fs");
setInterval(() => {
fs.writeFileSync("/tmp/worker.heartbeat", new Date().toISOString());
}, 30000);
Performance
- Keep health check commands fast. Target under 1 second execution time:
# Fast: simple HTTP check
curl -sf -m 2 http://localhost:3000/health
# Slow: database query
psql -c "SELECT count(*) FROM large_table" # Don't do this
- Use
--start-periodto avoid false negatives during boot. Set it to your app’s typical startup time plus 50 percent margin:
# App takes ~20s to boot, set start-period to 30s
HEALTHCHECK --start-period=30s --interval=30s --timeout=5s --retries=3 \
CMD curl -f http://localhost:3000/health
- Avoid health checks that write to disk. Each check runs frequently and can fill disk with logs:
# Bad: writes to disk every 30s
HEALTHCHECK CMD curl -f http://localhost:3000/health >> /var/log/health.log
# Good: no disk writes
HEALTHCHECK CMD curl -sf http://localhost:3000/health
Best Practices
- Always add a
HEALTHCHECKto production Dockerfiles — without it, “running” is all Docker can promise. - Set
--start-periodto your app’s real boot time plus margin (10-30s covers most apps; JVM apps may need 60s+). - Use
--interval=30sfor general services and10sonly for infrastructure where seconds matter. Every interval is a request against your app. - Keep
--timeoutshort (3-10s). A probe that hangs is worse than no probe — it never returns the failure signal you configured it for. - Create a dedicated
/healthendpoint that returns 200 with no side effects: no DB queries, no cache writes, no auth checks. - Probe the app itself, not merely the port — a listening socket still accepts connections while the event loop sits stuck.
- Use
depends_onwithcondition: service_healthyin Compose for startup ordering. - For databases, use built-in tools (
pg_isready,redis-cli ping) instead of HTTP — they’re already in the image and know the protocol.
Common Mistakes
- Not setting
--start-period. Slow-starting apps get marked unhealthy before they finish booting — the classic JVM and Rails problem. - Pointing the health check at the database. It adds load on every interval and can cause cascading failures when the DB hiccups.
- Setting
--intervaltoo low (1-5s). It wastes CPU and can overload the app with health requests. - Not creating a dedicated health endpoint. Checking
/might return 200 even when the API is broken — home pages often work while business logic doesn’t. - Forgetting to install curl or wget in the image. The probe dies with exit 127 and the container flips to unhealthy over a missing binary, not over anything your app did.
- Assuming Docker restarts unhealthy containers. Plain
docker rundoesn’t — you need Swarm, Kubernetes probes, or a watcher like autoheal for that. - Expecting Kubernetes to run
HEALTHCHECK. It doesn’t; define liveness and readiness probes in the pod spec instead. - Not using
depends_onwithcondition: service_healthy. Containers start before dependencies are ready.
Frequently Asked Questions
What happens when a container is marked unhealthy?
In plain Docker, nothing automatic — docker ps shows (unhealthy) and the state is queryable via docker inspect, that's it. Docker Swarm replaces unhealthy tasks with fresh ones. Kubernetes never sees the flag: it ignores HEALTHCHECK and applies its own liveness/readiness probes from the pod spec.
Should I use the same endpoint for liveness and readiness?
No. Liveness checks if the app is alive (should be cheap, no dependencies). Readiness checks if the app can serve requests (may check database connectivity). Use /health for liveness and /ready for readiness — mixing them causes restarts when the real problem is a saturated dependency.
Can I disable a health check from the base image?
Yes. Use HEALTHCHECK NONE in your Dockerfile to disable inherited health checks.
How do I check container health from the CLI?
docker inspect --format='{{.State.Health.Status}}' <container-name>
This returns healthy, unhealthy, or starting.
Why is my container stuck in "starting"?
Either the start-period hasn't finished, or the probe dies before your app is even tested. Run docker inspect --format='{{json .State.Health}}' <container> and read the probe output — a missing curl or wget (exit 127) is the usual suspect, followed by the app listening on a different port than the one the check hits.
What's the difference between HEALTHCHECK and a restart policy?
HEALTHCHECK reports whether the app inside is functioning. A restart policy reacts to the container exiting — it says nothing about an app that's alive but hung. They complement each other: the restart policy handles crashes, the health check surfaces the zombie state, and something external (Swarm, K8s probes, autoheal) acts on it.
Related Resources
Health Check Endpoint
How to implement a production-ready health check endpoint for monitoring and load balancers.
PatternHealth Check Pattern: Expose Liveness and Readiness Probes
Implement liveness and readiness probes for container orchestrators. Covers Kubernetes probe config, dependency checks, and graceful degradation.
RecipeDocker Multi-Stage Build Optimization for Smaller Images
Cut Docker image size and build time with multi-stage builds, smarter layer ordering, BuildKit cache mounts, and a lean .dockerignore.
RecipeOverride Docker Compose Configs per Environment
How to use Docker Compose override files for environment-specific configurations, covering dev, test, staging, production, profiles, and secrets.
RecipeDocker Network Isolation and Inter-Container Security
Secure inter-container communication with custom Docker networks, network segmentation, and access control policies.
DocDeployment Checklist Template
A copy-paste verification checklist for safe production deployments, from pre-merge tests to post-release monitoring.