Production deployment patterns
Graceful shutdown, prod config, rollouts, readiness probes, and ship-with-confidence checks.
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.
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__ == "__ma…
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.
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.wfi…
How to Mock a Dependency for Readiness Probe in Python
Use unittest.mock.Mock to simulate a dependency's readiness check response for testing a service's is_ready method without hitting a real connection.
import time
import unittest
from unittest.mock import Mock
class Service:
def __init__(self, dependency):
self.dependency = dependency
def is_ready(self):
try:
result = self.dependency.check()
return result == "ready"
except Exception:
return False
…
How to Mock an Ingress TLS Certificate Manager in Python
Build a mock TLS certificate manager for ingress that issues, checks, and renews certificates with expiry tracking — useful for testing deployment workflows before touching real infrastructure.
import ssl
import socket
from datetime import datetime, timedelta
class TLSCertManager:
def __init__(self, hostname):
self.hostname = hostname
self.certificates = {}
def request_certificate(self, domain, days_valid=90):
"""Mock a certificate issuance request that stores a cert with e…
How to Simulate Blue-Green Deployment Switch in Python
A mock Blue-Green deployment class that deploys new versions to an inactive environment, runs a health check, switches traffic, and supports rollback in Python.
import random
import time
class BlueGreenDeployment:
def __init__(self, initial_env="blue"):
self.environments = {"blue": "v1.0", "green": "v1.0"}
self.active_env = initial_env
self.running = True
def deploy_new_version(self, version, target_env):
if target_env == self.active_…
How to Smoke Test a Deployment in Python with unittest.mock
Run a post-deploy smoke test by mocking the deployment status check to verify your health-check logic returns PASS/FAIL.
import unittest
from unittest.mock import Mock, patch
class DeploymentService:
def check_status(self):
return "unknown"
def smoke_test_deploy():
service = DeploymentService()
with patch.object(service, "check_status", return_value="healthy") as mock_check:
status = service.check_status()
…
How to mock resource request limits in Python
A Python class that simulates CPU and memory limit checks for resource requests, returning clear acceptance or rejection messages.
class ResourceLimits:
def __init__(self, cpu_limit, memory_limit):
self.cpu_limit = cpu_limit
self.memory_limit = memory_limit
def check_request(self, cpu, memory):
if cpu > self.cpu_limit:
return "CPU limit exceeded: {cpu} > {limit}".format(cpu=cpu, limit=self.cpu_limit)
…
How to simulate a Jenkins pipeline in Python
Simulate a Jenkins-style pipeline in Python by running sequential stages and checking aggregate success.
def run_stage(name, duration, fn):
print(f"[Pipeline] Running stage: {name}")
result = fn()
print(f"[Pipeline] Stage '{name}' completed in {duration}s -> {result}")
return result
def build_project():
print(" compiling source...")
return "BUILD_OK"
def run_tests():
print(" executing unit…
How to simulate a database migration init container mock in Python
A mock init container that runs environment checks and a staged database migration job before the main application starts, printing progress to stdout.
```python
class MigrationJob:
def __init__(self, name, steps):
self.name = name
self.steps = steps
self.current_step = 0
self.status = "pending"
def run(self):
print(f"Initializing migration job: {self.name}")
for step in self.steps:
self.current_ste…
PodDisruptionBudget minAvailable in Python
Simulate a Kubernetes PodDisruptionBudget check for minAvailable and maxUnavailable constraints with a Python class.
class PodDisruptionBudget:
def __init__(self, name, min_available=None, max_unavailable=None):
self.name = name
self.min_available = min_available
self.max_unavailable = max_unavailable
def check_availability(self, ready_pods):
if self.min_available is not None:
ret…
Browse by section
Each section groups closely related Python snippets.
Production deployment patterns — Python code examples
What you will find here
This page collects production deployment patterns snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.