Skip to content
Automation

Docker Health Check Script: Auto-Restart Unhealthy Containers in Python (2027)

Copy-paste a production Docker health check script in Python to monitor container health, auto-restart unhealthy services, and send webhook alerts in 2027.

Updated: 14 min read 3 views
Share: Facebook X LinkedIn WhatsApp

A production-ready docker health check script closes the biggest reliability gap in standalone Docker deployments: automatically recovering deadlocked containers that pass process-level checks but fail real application probes. If you run Docker Compose or single-host containers outside Swarm or Kubernetes, Docker Engine executes your HEALTHCHECK command and marks broken services as unhealthy, yet it takes zero corrective action. Your API stops answering requests, database workers hang on exhausted pools, and restart: unless-stopped stays completely idle because PID 1 never exited. Built for Linux (Ubuntu 22.04+, Debian 12+, RHEL 9+) and macOS hosts running Python 3.10+ and Docker Engine 24+, the script below inspects container health states through the official Docker SDK, enforces opt-in labels and restart cooldowns, supports a safe --dry-run mode, and dispatches instant Slack or Discord webhook alerts. You can copy, configure, and run it in under five minutes.

Key Takeaways & Script Specs

  • Runtime & Dependencies: Python 3.10+, docker SDK (7.x), and requests (optional for webhook alerts).
  • Target Environments: Standalone Docker Engine and Docker Compose stacks on Linux or macOS.
  • Execution Time: Under 50 ms per polling cycle; configurable check interval (default 30 seconds).
  • Safety Controls: Opt-in label filtering (com.myscrpts.autoheal=true), per-container cooldown window, max-restart circuit breaker, and --dry-run flag.

Why Docker Restart Policies Miss Unhealthy Containers

Most engineers assume setting restart: always or restart: unless-stopped in a Compose file protects their stack from application hangs. In reality, Docker’s native restart policies only monitor the exit code of the container’s root process (PID 1). When a Python Gunicorn worker deadlocks, a Node.js event loop blocks on synchronous I/O, or a Redis sidecar drops its upstream socket while keeping the process alive, PID 1 never terminates. From the host kernel’s perspective, the container is still running.

To detect those silent failures, Docker provides the HEALTHCHECK instruction, documented in the Docker Dockerfile HEALTHCHECK reference. Docker runs a probe command inside the container at a fixed interval and maps the exit code to one of four states: none, starting, healthy, or unhealthy. While Swarm mode automatically replaces unhealthy tasks, standalone Docker Engine treats the unhealthy flag strictly as passive metadata. Without an external watchdog script or orchestrator watching that state, a zombie container stays in unhealthy limbo indefinitely until an engineer manually runs docker restart—often hours after users notice downtime.

Architecture and Execution Flow of the Watchdog Script

A naive bash loop that blindly restarts every unhealthy container on a one-minute cron schedule creates more outages than it prevents. If a database migration fails or an upstream API key expires, restarting the container every 60 seconds triggers a destructive crash loop that burns CPU, floods logs, and masks the root cause. A production-grade watchdog needs state memory, opt-in scoping, and circuit-breaking logic.

Our Python monitor connects to the local Docker daemon via the Docker SDK for Python containers documentation and evaluates every running container against four sequential gates before issuing a restart:

+-------------------------------------------------------------------+

|  1. Poll Docker Daemon (docker.from_env().containers.list())      |
                                  |
                                  v
+-------------------------------------------------------------------+
|  2. Filter Scope: Opt-in label present OR --all-containers flag?  |
+---------------------------------+---------------------------------+
                                  | (Match)
                                  v
+-------------------------------------------------------------------+
|  3. Inspect State.Health.Status == "unhealthy"                    |
+---------------------------------+---------------------------------+
                                  | (Unhealthy)
                                  v
+-------------------------------------------------------------------+
|  4. Check Cooldown & Max Restarts Circuit Breaker                 |
|     - Within cooldown? -> Skip & log remaining wait               |
|     - Exceeded max restarts in window? -> Alert & Trip Breaker    |
+---------------------------------+---------------------------------+
                                  | (Clear)
                                  v
+-------------------------------------------------------------------+
|  5. Execute Restart (or log [DRY-RUN]) + Send Webhook Alert       |
+-------------------------------------------------------------------+

Notice how cleanly this separates detection from recovery. By reading Docker’s native State.Health.Status attribute rather than running duplicate HTTP checks from outside the container, the script respects each service’s own start_period, timeout, and retries configuration. You keep your health definitions inside your Dockerfile or compose.yml, while the Python script acts as a deterministic control plane—much like pairing automated Linux server backups with dedicated verification checks.

Comparing Container Auto-Recovery Approaches in 2027

Before deploying a custom watchdog, it helps to compare how the four standard recovery patterns behave on single-node and small-cluster servers in 2027. Each option trades simplicity against observability and blast-radius control.

Recovery ApproachDetects Hung ProcessesCooldown & Circuit BreakerWebhook AlertingOperational Overhead
Native restart: unless-stoppedNo (PID 1 exit only)Built-in backoffNoneZero (built into Compose)
Docker Swarm ModeYes (replaces tasks)Yes (restart policy)External toolingHigh (requires Swarm cluster)
willfarrell/autoheal ContainerYes (label-based)Basic interval onlyLimited / externalLow (single sidecar image)
Custom Python WatchdogYes (Docker SDK)Full cooldown + capNative Slack/DiscordLow (single Python script)

While lightweight sidecar images work for home labs, production servers benefit from explicit circuit-breaker thresholds and native webhook payloads that tell your team exactly which container restarted, how many times it failed in the last hour, and what the last healthcheck log line reported. You can also combine this watchdog with other free developer CLI tools like lazydocker or ctop during live incident triage.

Prerequisites and Virtual Environment Setup

Always isolate automation dependencies inside a dedicated virtual environment rather than polluting the system Python installation. On Ubuntu 24.04+ and Debian 12+, PEP 668 blocks global pip install calls by default, making a virtual environment mandatory for clean deployments.

Run the following commands to create a dedicated directory, initialize a virtual environment, and install the Docker SDK and requests library:

sudo mkdir -p /opt/docker-health-monitor
sudo chown "$USER":"$USER" /opt/docker-health-monitor
cd /opt/docker-health-monitor

python3 -m venv .venv
source .venv/bin/activate

pip install --upgrade pip
pip install "docker>=7.1.0,<8.0.0" "requests>=2.32.0,<3.0.0"

Verify that your current user can communicate with the Docker daemon socket without sudo by running docker ps. If you see a permission denied error on /var/run/docker.sock, add your service user to the docker group (or better yet, route through a read/restart-scoped socket proxy, covered in the security hardening section below).

Complete Production Python Docker Health Check Script

Save the following script as /opt/docker-health-monitor/docker_health_monitor.py. It uses Python’s standard argparse module for CLI flags and follows the Python logging cookbook for clean stdout/journald output. Every restart is guarded by a configurable cooldown window and a sliding-window circuit breaker so broken containers cannot loop forever.

#!/usr/bin/env python3
"""
Production Docker Health Check & Auto-Restart Monitor (2027)
Polls running containers via Docker SDK, restarts unhealthy services with
cooldown and circuit-breaker protection, and sends optional webhook alerts.
"""

import argparse
import logging
import os
import signal
import sys
import time
from collections import defaultdict, deque
from datetime import datetime, timezone
from typing import Deque, Dict, Optional

import docker
import requests
from docker.errors import APIError, DockerException, NotFound

LOG_FORMAT = "%(asctime)s [%(levelname)s] %(message)s"
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT, stream=sys.stdout)
logger = logging.getLogger("docker_health_monitor")

RUNNING = True

def handle_signal(signum: int, _frame) -> None:
"""Gracefully stop the polling loop on SIGINT or SIGTERM."""
global RUNNING
logger.info("Received signal %d; shutting down cleanly.", signum)
RUNNING = False

def send_webhook(webhook_url: Optional[str], message: str, timeout: int = 5) -> None:
"""Send a JSON alert payload compatible with Slack and Discord webhooks."""
if not webhook_url:
return

payload = {"text": message, "content": message}
try:
    response = requests.post(webhook_url, json=payload, timeout=timeout)
    response.raise_for_status()
except requests.RequestException as exc:
    logger.warning("Webhook delivery failed: %s", exc)

def get_last_health_log(attrs: dict) -> str:
"""Extract the most recent HEALTHCHECK output line for diagnostics."""
health = attrs.get("State", {}).get("Health", {})
logs = health.get("Log", [])
if not logs:
return "No healthcheck output recorded."
last_entry = logs[-1]
exit_code = last_entry.get("ExitCode", "?")
output = (last_entry.get("Output") or "").strip().replace("\n", " ")
return f"exit={exit_code} output='{output[:200]}'"

class HealthMonitor:
def init(
self,
client: docker.DockerClient,
label_key: str,
all_containers: bool,
cooldown_seconds: int,
max_restarts: int,
window_seconds: int,
restart_timeout: int,
webhook_url: Optional[str],
dry_run: bool,
) -> None:
self.client = client
self.label_key = label_key
self.all_containers = all_containers
self.cooldown_seconds = cooldown_seconds
self.max_restarts = max_restarts
self.window_seconds = window_seconds
self.restart_timeout = restart_timeout
self.webhook_url = webhook_url
self.dry_run = dry_run

    self.last_restart: Dict[str, float] = {}
    self.restart_history: Dict[str, Deque[float]] = defaultdict(deque)
    self.tripped_breakers: set[str] = set()

def is_eligible(self, container) -> bool:
    """Check whether the container opts into auto-recovery."""
    if self.all_containers:
        return True
    labels = container.labels or {}
    return labels.get(self.label_key, "").lower() == "true"

def prune_history(self, cid: str, now: float) -> None:
    """Drop restart timestamps older than the sliding circuit-breaker window."""
    history = self.restart_history[cid]
    while history and (now - history[0]) > self.window_seconds:
        history.popleft()

def check_once(self) -> None:
    """Inspect all running containers and act on unhealthy targets."""
    now = time.monotonic()
    try:
        containers = self.client.containers.list()
    except DockerException as exc:
        logger.error("Failed to list Docker containers: %s", exc)
        return

    for container in containers:
        if not self.is_eligible(container):
            continue

        try:
            container.reload()
        except NotFound:
            continue
        except APIError as exc:
            logger.warning("Could not reload %s: %s", container.name, exc)
            continue

        attrs = container.attrs
        health_state = attrs.get("State", {}).get("Health", {}).get("Status")
        if not health_state:
            continue

        cid = container.id
        if health_state == "healthy":
            if cid in self.tripped_breakers:
                self.tripped_breakers.discard(cid)
                logger.info("Container '%s' recovered; circuit breaker reset.", container.name)
            continue

        if health_state != "unhealthy":
            continue

        self.prune_history(cid, now)

        if len(self.restart_history[cid]) >= self.max_restarts:
            if cid not in self.tripped_breakers:
                self.tripped_breakers.add(cid)
                diag = get_last_health_log(attrs)
                alert = (
                    f"[CIRCUIT BREAKER] Container '{container.name}' hit "
                    f"{self.max_restarts} restarts in {self.window_seconds}s. "
                    f"Manual intervention required. Last probe: {diag}"
                )
                logger.error(alert)
                send_webhook(self.webhook_url, alert)
            continue

        last_ts = self.last_restart.get(cid, 0.0)
        elapsed = now - last_ts
        if last_ts > 0 and elapsed < self.cooldown_seconds:
            remaining = int(self.cooldown_seconds - elapsed)
            logger.info(
                "Container '%s' is unhealthy but in cooldown (%ds remaining).",
                container.name,
                remaining,
            )
            continue

        diag = get_last_health_log(attrs)
        timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%SZ")

        if self.dry_run:
            logger.info(
                "[DRY-RUN] Would restart unhealthy container '%s' (%s). %s",
                container.name,
                container.short_id,
                diag,
            )
            continue

        logger.warning(
            "Restarting unhealthy container '%s' (%s). %s",
            container.name,
            container.short_id,
            diag,
        )
        try:
            container.restart(timeout=self.restart_timeout)
            self.last_restart[cid] = now
            self.restart_history[cid].append(now)
            msg = (
                f"[AUTOHEAL] Restarted unhealthy container '{container.name}' "
                f"at {timestamp} (attempt {len(self.restart_history[cid])}/{self.max_restarts}). "
                f"Probe: {diag}"
            )
            logger.info(msg)
            send_webhook(self.webhook_url, msg)
        except APIError as exc:
            err_msg = f"[ERROR] Failed to restart '{container.name}': {exc}"
            logger.error(err_msg)
            send_webhook(self.webhook_url, err_msg)

def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Monitor Docker container health and auto-restart unhealthy services."
)
parser.add_argument(
"--interval",
type=int,
default=int(os.getenv("CHECK_INTERVAL", "30")),
help="Polling interval in seconds (default: 30)",
)
parser.add_argument(
"--cooldown",
type=int,
default=int(os.getenv("COOLDOWN_SECONDS", "120")),
help="Minimum seconds between restarts for the same container (default: 120)",
)
parser.add_argument(
"--max-restarts",
type=int,
default=int(os.getenv("MAX_RESTARTS", "3")),
help="Max restarts allowed within --window before tripping circuit breaker (default: 3)",
)
parser.add_argument(
"--window",
type=int,
default=int(os.getenv("RESTART_WINDOW", "1800")),
help="Sliding window in seconds for max restarts (default: 1800)",
)
parser.add_argument(
"--label",
default=os.getenv("AUTOHEAL_LABEL", "com.myscrpts.autoheal"),
help="Container label required for opt-in auto-restart (default: com.myscrpts.autoheal)",
)
parser.add_argument(
"--all-containers",
action="store_true",
help="Monitor all containers with a HEALTHCHECK regardless of labels",
)
parser.add_argument(
"--once",
action="store_true",
help="Run a single inspection pass and exit",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Log containers that would be restarted without executing restarts",
)
return parser.parse_args()

def main() -> int:
signal.signal(signal.SIGINT, handle_signal)
signal.signal(signal.SIGTERM, handle_signal)

args = parse_args()
webhook_url = os.getenv("WEBHOOK_URL")

try:
    client = docker.from_env()
    client.ping()
except DockerException as exc:
    logger.critical("Cannot connect to Docker daemon: %s", exc)
    return 1

monitor = HealthMonitor(
    client=client,
    label_key=args.label,
    all_containers=args.all_containers,
    cooldown_seconds=args.cooldown,
    max_restarts=args.max_restarts,
    window_seconds=args.window,
    restart_timeout=15,
    webhook_url=webhook_url,
    dry_run=args.dry_run,
)

logger.info(
    "Started Docker health monitor (interval=%ds, cooldown=%ds, max_restarts=%d/%ds, dry_run=%s)",
    args.interval,
    args.cooldown,
    args.max_restarts,
    args.window,
    args.dry_run,
)

if args.once:
    monitor.check_once()
    return 0

while RUNNING:
    monitor.check_once()
    for _ in range(args.interval):
        if not RUNNING:
            break
        time.sleep(1)

return 0

if __name__ == "__main__":
sys.exit(main())

Before running the daemon continuously, test your configuration safely with --once --dry-run. That single pass verifies Docker socket connectivity, confirms which containers carry the com.myscrpts.autoheal=true label, and prints any unhealthy diagnostics without touching live workloads. If you also run local Python automation workflows on the same host, you can pipe these JSON webhook alerts into an internal triage bot or Slack incident channel.

chmod +x /opt/docker-health-monitor/docker_health_monitor.py
/opt/docker-health-monitor/.venv/bin/python /opt/docker-health-monitor/docker_health_monitor.py --once --dry-run

To opt a service into automatic restarts, add the label and a side-effect-free healthcheck block inside your compose.yml file:

services:
  api:
    image: ghcr.io/example/api:latest
    restart: unless-stopped
    labels:
      - "com.myscrpts.autoheal=true"
    healthcheck:
      test: ["CMD", "curl", "-fsS", "http://localhost:8000/health"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 20s

Running as a Systemd Service or Cron Job

Running the monitor inside an interactive tmux session fails the moment your server reboots. For production Linux hosts, wrap the script in a systemd service with an isolated environment file so credentials like WEBHOOK_URL stay out of process argument lists. Just as you automate deployments with GitHub Actions CI/CD pipelines, automating daemon supervision ensures your recovery layer starts immediately after docker.service.

First, create an environment file at /opt/docker-health-monitor/.env with strict 0600 permissions:

cat <<'EOF' > /opt/docker-health-monitor/.env
CHECK_INTERVAL=30
COOLDOWN_SECONDS=120
MAX_RESTARTS=3
RESTART_WINDOW=1800
AUTOHEAL_LABEL=com.myscrpts.autoheal
WEBHOOK_URL=https://hooks.slack.com/services/REPLACE/ME/NOW
EOF
chmod 600 /opt/docker-health-monitor/.env

Next, create the systemd unit file at /etc/systemd/system/docker-health-monitor.service and enable it:

sudo tee /etc/systemd/system/docker-health-monitor.service >/dev/null <<'EOF'
[Unit]
Description=Docker Unhealthy Container Auto-Restart Monitor
After=docker.service
Requires=docker.service

[Service]
Type=simple
WorkingDirectory=/opt/docker-health-monitor
EnvironmentFile=/opt/docker-health-monitor/.env
ExecStart=/opt/docker-health-monitor/.venv/bin/python /opt/docker-health-monitor/docker_health_monitor.py
Restart=always
RestartSec=10
NoNewPrivileges=true
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable --now docker-health-monitor
sudo journalctl -u docker-health-monitor -f

If you prefer a stateless cron job instead of a persistent daemon (for example, on shared hosts where you only want a five-minute sweep), pass --once in your crontab. Note that stateless cron runs do not preserve in-memory cooldown dictionaries across invocations, so keep the systemd daemon approach whenever you need crash-loop circuit breakers.

Troubleshooting and Security Hardening

Even a clean watchdog script can hit edge cases on busy hosts. Watch out for these three operational pitfalls and apply the corresponding hardening rules before rolling out across production nodes:

  • Premature Restarts During Slow Boot: If a Java, Spring Boot, or ML inference container takes 45 seconds to warm up, Docker marks it unhealthy prematurely unless start_period is set high enough. Always set start_period above your p99 cold-start duration so Docker ignores probe failures during initialization.
  • Docker Socket Privilege Exposure: Granting direct access to /var/run/docker.sock gives a process root-equivalent control over the host. If you run this monitor inside a container or under an unprivileged service user, place a lightweight Docker socket proxy (such as tecnativa/docker-socket-proxy) in front of the socket with only CONTAINERS=1 and POST=1 enabled, and point DOCKER_HOST=tcp://socket-proxy:2375 at it.
  • Webhook Timeout Blocking: Never omit the timeout=5 parameter on requests.post(). If Slack or Discord experiences an outage, an un-bounded HTTP request will freeze your entire health-monitoring loop and delay restarts for other containers.

Frequently Asked Questions

Why does Docker not restart unhealthy containers automatically?

Outside of Docker Swarm mode, Docker Engine treats the HEALTHCHECK status as informational metadata only. Native restart policies such as restart: unless-stopped only trigger when the container’s root process (PID 1) exits, so deadlocked or hung services remain running in an unhealthy state until an external script or orchestrator restarts them.

How does the cooldown and circuit breaker prevent crash loops?

The script tracks the last restart timestamp per container ID and enforces a minimum cooldown (default 120 seconds) between restarts. It also records restart attempts in a sliding 30-minute window; if a container hits the maximum allowed restarts (default 3), the circuit breaker trips, halts further restarts, and sends a high-priority webhook alert.

Should I monitor all containers or use an opt-in label?

Using an opt-in label such as com.myscrpts.autoheal=true is strongly recommended for production hosts. Stateful databases or containers running long schema migrations can corrupt data if restarted mid-flight, whereas stateless web workers and API gateways recover safely.

Can I run this Python health check script inside a Docker container?

Yes. Package the script with a minimal python:3.12-slim image and either mount /var/run/docker.sock:ro (with write access only if restarting directly) or point DOCKER_HOST at a restricted Docker socket proxy container for stronger isolation.

Does –dry-run modify any running containers?

No. Passing –dry-run executes the full container discovery, label filtering, and health state inspection pipeline, then logs what it would restart along with the last healthcheck probe output without calling container.restart().

What happens if a container has no HEALTHCHECK defined?

Containers without a Dockerfile HEALTHCHECK or Compose healthcheck block do not populate State.Health.Status. The script detects the missing health field and safely skips those containers without raising errors.

Leave a Reply

Your email address will not be published. Required fields are marked *

Stay ahead of the curve. Zero spam.

Get our weekly curation of tested scripts, DevOps blueprints, and new dev tools.