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.
Python code
17 linesimport 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
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
- Use `requests` library if curl is not installed
- Check a TCP port with a socket connection instead of HTTP
- 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
More from Production deployment patterns
- Auto Rollback on Error Rate Exceeded in Python medium
- Automate Semantic Versioning with Conventional Commits in Python medium
- Design a Data Helper for Beginners in Python easy
- Generate a Mock Artifact Version Tag in Python easy
- Generate a docker-compose.yml with mock services in Python easy
- How to Attach an SBOM to a Release in Python (Mock) easy
Keep learning
Related tutorials and quizzes for this topic.