Reference library

Production deployment patterns

Graceful shutdown, prod config, rollouts, readiness probes, and ship-with-confidence checks.

41 matches
Production deployment patterns easy

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.

docker healthcheck subprocess
Python
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…
15 0 Open
Production deployment patterns easy

Generate a Mock Artifact Version Tag in Python

Creates a mock build artifact version tag from a branch name and build number, with a date stamp.

artifact versioning ci
Python
import re
from datetime import datetime

def mock_version_tag(branch_name: str, build_number: int) -> str:
    """Generate a mock build artifact version tag from branch and build number."""
    branch_slug = re.sub(r'[^a-zA-Z0-9]+', '-', branch_name).strip('-').lower()
    date_part = datetime.utcnow().strftime('%Y%m%…
13 0 Open
Production deployment patterns easy

Generate a docker-compose.yml with mock services in Python

Build a docker-compose.yml string from a Python dict of service names and images, then write it to a file.

docker compose yaml
Python
import yaml
from pathlib import Path

def generate_mock_compose(services: dict) -> str:
    compose = {
        "version": "3.9",
        "services": {}
    }
    
    for name, image in services.items():
        compose["services"][name] = {
            "image": image,
            "container_name": f"mock-{name}",
  …
17 0 Open
Production deployment patterns easy

How to Attach an SBOM to a Release in Python (Mock)

A mock function that attaches a Software Bill of Materials (SBOM) to a GitHub-style release by counting its components and marking the upload as attached.

sbom release json
Python
import json
from pathlib import Path


def attach_sbom_mock(sbom_path: Path, release_tag: str, artifact_name: str) -> dict:
    """Mock attaching an SBOM to a release, returning the simulated upload result."""
    sbom = json.loads(sbom_path.read_text())
    return {
        "release_tag": release_tag,
        "artifa…
14 0 Open
Production deployment patterns medium

How to Build a GitOps Argo CD Sync Mock in Python

Simulate Argo CD-style GitOps deployment sync with Python dataclasses, random success rates, and force-sync retry logic.

gitops argo-cd deployment
Python
import random
import time
from dataclasses import dataclass, field
from typing import List, Dict


@dataclass
class Application:
    name: str
    source_repo: str
    target_revision: str
    synced: bool = False
    health_status: str = "Healthy"
    history: List[Dict] = field(default_factory=list)

    def sync(se…
13 0 Open
Production deployment patterns easy

How to Build a Mock Trivy Image Scan Gate in Python

Simulate a Trivy image scan and enforce a security gate that fails the pipeline when vulnerabilities meet or exceed a severity threshold.

trivy security ci-cd
Python
import json
import sys


def mock_trivy_scan(image_name, severity_threshold="HIGH"):
    """Simulate a Trivy image scan result."""
    mock_vulnerabilities = [
        {"ID": "CVE-2023-1234", "Severity": "HIGH", "Package": "openssl", "FixedVersion": "3.0.9"},
        {"ID": "CVE-2024-5678", "Severity": "CRITICAL", "Pa…
13 0 Open
Production deployment patterns easy

How to Build a Synthetic Monitor Mock in Python

Simulates a synthetic monitoring system in Python that collects latency samples, averages them, and reports service status as UP or DEGRADED.

monitoring dataclass simulation
Python
import random
import time
from dataclasses import dataclass, field
from statistics import mean


@dataclass
class SyntheticMonitor:
    service: str
    endpoint: str
    latency_ms: list[float] = field(default_factory=list)

    def check(self) -> float:
        latency = random.uniform(50.0, 250.0)
        self.late…
13 0 Open
Production deployment patterns easy

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.

http healthcheck mock-server
Python
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…
15 0 Open
Production deployment patterns easy

How to Deploy Staging Then Production in Python

Walk through a staged deployment mock that promotes from staging to production in sequence with Python.

deployment staging production
Python
import time

def deploy_environment(name: str) -> None:
    print(f"Deploying to {name}...")
    time.sleep(0.1)
    print(f"Deployed to {name} ✔")

def deploy_staging_then_prod() -> None:
    environments = ["staging", "production"]
    for env in environments:
        deploy_environment(env)
        if env == "stagi…
14 0 Open
Production deployment patterns easy

How to Implement a Manual Approval Gate Mock in Python

Simulates a manual approval workflow with threshold-based rules, random decisions for medium amounts, and logs each result with timing.

approval simulation workflow
Python
import random
import time


def approve_request(amount: float) -> bool:
    if amount <= 1000:
        return True
    if amount <= 5000:
        return random.random() < 0.7
    return False


def main():
    requests = [500, 1200, 7500, 3000, 50]
    for amount in requests:
        start = time.perf_counter()
      …
18 0 Open
Production deployment patterns medium

How to Mock Canary Deployment Traffic Split in Python

Simulate a canary deployment's stable/canary traffic split using deterministic request hashing to mock rollout behavior with precise percentage control.

canary-deployment traffic-split simulation
Python
class CanaryDeployment:
    def __init__(self, stable_weight: float = 0.9, canary_weight: float = 0.1):
        self.stable_weight = stable_weight
        self.canary_weight = canary_weight
        self.total_weight = stable_weight + canary_weight

    def route_request(self, request_id: int) -> str:
        """Route …
14 0 Open
Production deployment patterns easy

How to Mock Docker Image Non-Root User in Python

This Python class simulates Docker image layers and inspects whether the final user is a non-root user, returning UID, GID, and security status.

docker security mock
Python
from pathlib import Path


class DockerImageMock:
    def __init__(self, name, tag):
        self.name = name
        self.tag = tag
        self.layers = []
        self.user = "root"

    def add_file(self, path, content):
        self.layers.append({"file": path, "content": content})

    def set_user(self, usernam…
11 0 Open
Production deployment patterns medium

How to Mock Image Signing Cost in Python

Create a deterministic mock signing cost calculator that predicts resource usage for image signatures before real signing infrastructure is staged.

mock signing cost-model
Python
import math
import struct


def sign_image_cost(image_signature: bytes) -> int:
    """Deterministic mock signing cost based on image signature bytes."""
    if not image_signature:
        raise ValueError("Empty image signature")
    digest = 0
    for byte in image_signature:
        digest = (digest * 31 + byte) &…
14 0 Open
Production deployment patterns medium

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.

kubernetes mock testing
Python
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…
14 0 Open
Production deployment patterns medium

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.

kubernetes clusterip mock
Python
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…
13 0 Open
Production deployment patterns easy

How to Mock Multi-Stage Docker Builds in Python

Simulate a multi-stage Docker build in pure Python using classes and temp directories to understand how build stages copy artifacts into a final image.

docker multi-stage simulation
Python
# Simulate multi-stage Docker build with pure Python
from pathlib import Path
import tempfile
import shutil

class BuildContext:
    """Mimics a Docker build context with stages."""
    
    def __init__(self, name):
        self.name = name
        self.files = {}
    
    def add_file(self, dest, content):
        s…
14 0 Open
Production deployment patterns easy

How to Mock Terraform Plan and Apply in Python

This code provides a lightweight Python mock of Terraform's plan and apply commands, helping you simulate infrastructure changes without real cloud resources.

terraform mock simulation
Python
class MockTerraform:
    def __init__(self):
        self.plans = [
            {"id": 1, "action": "create", "resource": "aws_instance.web"},
            {"id": 2, "action": "update", "resource": "aws_s3_bucket.data"},
            {"id": 3, "action": "destroy", "resource": "aws_iam_user.legacy"}
        ]
        sel…
14 0 Open
Production deployment patterns easy

How to Mock a CI Pipeline with Build, Test, and Deploy Stages in Python

Simulate a three-stage CI pipeline (build, test, deploy) in Python with random pass/fail logic, early exit on failure, and measured stage durations.

ci-cd simulation dataclasses
Python
import time
import random
from dataclasses import dataclass


@dataclass
class StageResult:
    name: str
    status: str
    duration: float


def run_stage(name: str, success_chance: float = 0.9) -> StageResult:
    """Simulate a pipeline stage with random success/failure."""
    start = time.time()
    time.sleep(r…
14 0 Open
Production deployment patterns easy

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.

containers testing mocking
Python
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…
14 0 Open
Production deployment patterns easy

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.

unittest.mock mock readiness probe
Python
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
…
17 0 Open
Production deployment patterns easy

How to Mock a Dockerfile Multi-Stage Build in Python

Simulate a Dockerfile multi-stage build process in Python using dataclasses to validate stage ordering and file availability before you write the real Dockerfile.

dockerfile multi-stage simulation
Python
from dataclasses import dataclass
from pathlib import Path


@dataclass
class BuildStage:
    name: str
    base_image: str
    files: list[str]
    commands: list[str]


def run_build(stage: BuildStage, context_dir: Path):
    print(f"=== Stage: {stage.name} (base: {stage.base_image}) ===")
    for file in stage.file…
14 0 Open
Production deployment patterns easy

How to Mock a Feature Flag Rollout Percentage in Python

Simulate a percentage-based feature flag rollout by hashing a user ID to deterministically enable features for a subset of users.

feature-flags rollout deterministic
Python
import random
from dataclasses import dataclass


@dataclass
class FeatureFlag:
    name: str
    rollout_percentage: int


def is_feature_enabled(feature_flag: FeatureFlag, user_id: str) -> bool:
    hashed_id = hash(user_id) % 100
    return hashed_id < feature_flag.rollout_percentage


if __name__ == "__main__":
  …
11 0 Open
Production deployment patterns easy

How to Mock a GitHub Actions Workflow in Python

Build a dataclass-based model of a GitHub Actions workflow and simulate its execution to validate steps and outputs before deployment.

github-actions dataclasses mock
Python
import json
from dataclasses import dataclass, asdict
from typing import List, Dict, Any


@dataclass
class Step:
    name: str
    run: str


@dataclass
class Job:
    name: str
    steps: List[Step]
    runs_on: str = "ubuntu-latest"


@dataclass
class Workflow:
    name: str
    jobs: List[Job]

    def to_github_a…
13 0 Open
Production deployment patterns easy

How to Mock a Kubernetes Rolling Update with maxSurge in Python

Simulate a Kubernetes rolling update with maxSurge policy, tracking peak and final replica counts during roll transitions.

kubernetes rolling-update maxsurge
Python
from collections import deque

class RollingUpdateMaxSurge:
    def __init__(self, replicas, max_surge):
        self.replicas = replicas
        self.max_surge = max_surge
        self.available = replicas
        self.history = deque()

    def roll(self, desired_replicas):
        """
        Simulate a rolling upd…
13 0 Open

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.