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.

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

Python code

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

stdout
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

  1. Use `ThreadingHTTPServer` to handle concurrent probe requests
  2. 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

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.