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.

Easy Python 3.9+ Aug 9, 2026 Modern tooling 15 views 0 copies

Python code

26 lines
Python 3.9+
import 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

stdout
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

  1. Use `random.choice` to randomly pick healthy/unhealthy for each service
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Modern tooling

Related tutorials and quizzes for this topic.