How to Mock docker compose up Healthcheck in Python
Simulate docker compose up with a healthcheck cycle using Python loops, delays, and simulated service statuses.
Python code
26 linesimport subprocess
import time
def run_healthcheck():
"""Mock a docker compose up with a healthcheck cycle."""
services = ["web", "db", "cache"]
print("Starting docker compose services...")
for service in services:
print(f"[{service}] starting...")
time.sleep(0.1)
print(f"[{service}] healthy")
print("\nHealth check cycle:")
for attempt in range(1, 4):
status = f"Attempt {attempt}: "
for service in services:
healthy = attempt % 2 == 0 or service == "db"
status += f"{service}={'healthy' if healthy else 'unhealthy'}, "
print(status.rstrip(", "))
time.sleep(0.2)
print("\nFinal: all containers healthy")
if __name__ == "__main__":
run_healthcheck()
Output
Starting docker compose services...
[web] starting...
[web] healthy
[db] starting...
[db] healthy
[cache] starting...
[cache] healthy
Health check cycle:
Attempt 1: web=unhealthy, db=healthy, cache=unhealthy
Attempt 2: web=healthy, db=healthy, cache=healthy
Attempt 3: web=unhealthy, db=healthy, cache=unhealthy
Final: all containers healthy
How it works
The time.sleep calls simulate the real delay a docker healthcheck would take before reporting status. Each service is checked over multiple attempts with attempt % 2 == 0 making two attempts healthy and one unhealthy. The db service is always healthy to model a stable dependency. The function prints a sequential startup and then per-attempt statuses, ending with a final all-healthy message. This pattern is handy for testing scripts that depend on waiting for multiple containers to come up.
Common mistakes
- Hard-coding statuses instead of varying them across attempts
- Using the real `docker compose up` subprocess when you only need a mock
- Forgetting to add delays, making the simulation unrealistically fast
Variations
- Use `random.choice` to randomly pick healthy/unhealthy for each service
- Replace `print` with logging to match production logging patterns
Real-world use cases
- Testing CI scripts that poll container health before running integration tests.
- Simulating a multi-service stack locally to debug orchestration logic.
- Training or demos for container orchestration concepts without Docker installed.
Sponsored
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.