How to Create a Liveness Probe HTTP Mock in Python
Build a lightweight HTTP server in Python that mimics a Kubernetes-style liveness endpoint, returning JSON health status for local testing.
Python code
37 linesimport http.server
import threading
import time
class LivenessHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/healthz":
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(b'{"status": "alive"}')
else:
self.send_response(404)
self.end_headers()
self.wfile.write(b'{"status": "not found"}')
def start_mock_server(port=8080):
server = http.server.HTTPServer(("127.0.0.1", port), LivenessHandler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
return server
if __name__ == "__main__":
mock = start_mock_server(port=8080)
print(f"Mock liveness probe running on http://127.0.0.1:8080/healthz")
time.sleep(0.2)
try:
from urllib.request import urlopen
response = urlopen("http://127.0.0.1:8080/healthz")
print(f"Response status: {response.status}")
print(f"Response body: {response.read().decode()}")
finally:
mock.shutdown()
Output
Mock liveness probe running on http://127.0.0.1:8080/healthz
Response status: 200
Response body: {"status": "alive"}
How it works
The http.server module provides a simple HTTP server that runs a custom BaseHTTPRequestHandler subclass. The do_GET method controls behavior for GET requests, returning a 200 with JSON for /healthz and 404 otherwise. Running the server in a daemon thread lets the main program continue execution, and urlopen verifies the endpoint works before shutting down.
Common mistakes
- Forgetting to send `end_headers()` before writing the response body
- Using `HTTPServer` directly instead of subclassing `BaseHTTPRequestHandler`
- Not calling `shutdown()` which can leave the server blocking the process
Variations
- Use `ThreadingHTTPServer` to handle concurrent probe requests
- Return a custom JSON payload with uptime or version info
Real-world use cases
- Testing Kubernetes readiness and liveness probe configuration during local development.
- Simulating a degraded service endpoint in integration tests to verify health-check retry logic.
- Providing a mocked /healthz route for a sidecar container in CI pipelines.
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
- Docker healthcheck CMD mock in Python easy
- Generate a Mock Artifact Version Tag in Python easy
- Generate a docker-compose.yml with mock services in Python easy
Keep learning
Related tutorials and quizzes for this topic.