Production deployment patterns
Graceful shutdown, prod config, rollouts, readiness probes, and ship-with-confidence checks.
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 Kubernetes Secret Mounts in Python
Create and inspect a mock Kubernetes secret volume mount using the official client library and unittest.mock.
import json
from kubernetes import client, config, watch
from unittest.mock import Mock, patch
def create_mock_mount_spec():
"""Create a mock Kubernetes secret volume mount."""
mock_client = Mock()
mock_client.api_version = "v1"
mock_client.kind = "Secret"
mock_client.metadata = {"name": "my-secre…
How to Mock Kubernetes Services with a ClusterIP Registry in Python
Simulate Kubernetes service discovery by assigning ClusterIP addresses to dataclass-defined services, with JSON export for inspection or testing.
import json
from dataclasses import dataclass, asdict
from typing import Dict, Optional
@dataclass
class Service:
name: str
namespace: str
cluster_ip: str
selector: Dict[str, str]
port: int
target_port: Optional[int] = None
class ClusterIPServiceRegistry:
_ip_counter = 0
def __init…
How to Mock a Container Registry in Python
Build an in-memory container registry mock with push, tag listing, and manifest retrieval logic for testing deployment tooling.
import json
from collections import defaultdict
class MockRegistry:
def __init__(self):
self.repositories = defaultdict(dict)
def push_image(self, repo: str, tag: str, layers: list[str]) -> None:
self.repositories[repo][tag] = {
"layers": layers,
"size": sum(len(layer…
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 a Slow Startup Probe for Fast Testing in Python
This code shows how to replace a slow startup probe's initialization with a mock to make tests run fast and reliably.
import time
from unittest.mock import Mock, patch
class StartupProbe:
def __init__(self, init_time):
self.init_time = init_time
self.ready = False
def initialize(self):
time.sleep(self.init_time)
self.ready = True
return self.ready
def run_startup_probe(probe):
…
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 mock S3 remote backend for Terraform in Python
Simulate a Terraform S3 remote backend using moto to write and read state files, enabling local testing without real AWS.
import boto3
from moto import mock_aws
import json
from pathlib import Path
@mock_aws
def demo_s3_remote_backend():
s3 = boto3.client("s3", region_name="us-east-1")
bucket = "terraform-state-bucket"
key = "env/prod/terraform.tfstate"
s3.create_bucket(Bucket=bucket)
# Simulate Terraform w…
Mock ConfigMap Mount Environment Variables in Python
Simulate reading environment variables from a Kubernetes ConfigMap-mounted directory and test it with mocks.
import os
import tempfile
from unittest.mock import patch
def load_config_from_mount(mount_path):
"""Simulate reading environment variables from a ConfigMap-mounted directory."""
config = {}
for filename in os.listdir(mount_path):
file_path = os.path.join(mount_path, filename)
if os.path.i…
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.