Docker SDK Python Container Healthcheck

Manage containers programmatically with the Docker SDK for Python, configuring health checks and waiting for healthy status before routing.

PythonCli Tooling

Code

snippet
import docker

client = docker.from_env()


def start_with_healthcheck(image: str, name: str, port: int) -> dict:
    container = client.containers.run(
        image,
        name=name,
        detach=True,
        ports={f'{port}/tcp': None},
        healthcheck={
            'test': ['CMD-SHELL', f'curl -sf http://localhost:{port}/healthz || exit 1'],
            'interval': 1_000_000_000,   # 纳秒:1 秒
            'timeout': 500_000_000,      # 纳秒:0.5 秒
            'retries': 5,
            'start_period': 3_000_000_000,
        },
        environment={'SERVICE_PORT': str(port)},
    )
    return {'id': container.short_id, 'name': name}


def wait_healthy(name: str, timeout: float = 30.0) -> bool:
    import time
    deadline = time.monotonic() + timeout

    while time.monotonic() < deadline:
        container = client.containers.get(name)
        health = container.attrs['State']['Health']['Status']
        if health == 'healthy':
            return True
        if health == 'unhealthy':
            return False
        time.sleep(0.5)
    return False


info = start_with_healthcheck('registry.example/app:2.4', 'app-blue', 8080)
print('started:', info)

if wait_healthy('app-blue'):
    print('traffic can be routed to app-blue now')
else:
    logs = client.containers.get('app-blue').logs(tail=40).decode()
    print('unhealthy, last logs:')
    print(logs[-600:])