Docker healthcheck CMD mock in Python

Runs a subprocess to curl a health endpoint and returns exit code 0 when healthy, 1 when unhealthy, mimicking a Docker HEALTHCHECK command.

Easy Python 3.9+ Aug 9, 2026 Production deployment patterns 14 views 0 copies

Python code

17 lines
Python 3.9+
import subprocess
import sys


def run_healthcheck() -> int:
    result = subprocess.run(["curl", "-fsS", "http://localhost:8080/health"], capture_output=True, text=True)
    if result.returncode == 0:
        print("healthy")
        return 0
    print("unhealthy", file=sys.stderr)
    return 1


if __name__ == "__main__":
    # Simulate a real healthcheck by checking a mock endpoint
    # In a real Docker HEALTHCHECK, this script would be the CMD
    exit(run_healthcheck())

Output

stdout
healthy

How it works

The script uses subprocess.run to execute the curl command with -fsS flags, which fail silently on server errors and suppress progress output. The return code from curl is captured and checked; 0 means the endpoint responded successfully, so the script prints 'healthy' and returns 0. If curl returns non-zero, the script prints 'unhealthy' to stderr and returns 1, which Docker interprets as a failed healthcheck. The if __name__ == "__main__" guard ensures the healthcheck runs only when the script is executed directly, not when imported.

Common mistakes

  • Forgetting to return 1 on failure, which Docker treats as unhealthy
  • Not capturing output, causing hangs if the endpoint is slow
  • Assuming `curl` is available in the container image

Variations

  1. Use `requests` library if curl is not installed
  2. Check a TCP port with a socket connection instead of HTTP
  3. Parse JSON response body for more detailed health status

Real-world use cases

  • As the HEALTHCHECK command in a Dockerfile to monitor a web service's readiness.
  • In a Kubernetes liveness probe script to report pod health status.
  • In a cron job to verify an internal service is still responding before running a dependent task.

Sponsored

Run this sample

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

Open editor

More from Production deployment patterns

Related tutorials and quizzes for this topic.