Docker SDK Python Container Healthcheck
Manage containers programmatically with the Docker SDK for Python, configuring health checks and waiting for healthy status before routing.
Code
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:])How the snippet works
Docker SDK Python Container Healthcheck comes down to the functions start_with_healthcheck and wait_healthy.
The cycling part of this snippet is while time.monotonic() < deadline.
Returns a newly built value, leaving the inputs as they were.
Points of care
- Plan for an install step:
dockeris a real dependency, resolved by the package manager.
Applying it
Signature: def start_with_healthcheck(image: str, name: str, port: int) -> dict
Running the file prints labeled results such as started:, traffic can be routed to app-blue now, unhealthy, last logs: — each operation’s effect is visible in the output.
Callers only need start_with_healthcheck — everything else stays internal.
Statements that matter
return {'id': container.short_id, 'name': name}
Interactive Tools for This Topic
FAQ
- Does `start_with_healthcheck` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- What does this need from the package registry?
- These are real dependencies: `docker`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.