Docker Hour 7: Deep Troubleshooting, Optimization and Advanced Topics

On the orders system from hour 6, run the loop "inject a fault → collect evidence → find the layer → fix → optimize": first build a methodology, then use nsenter / strace / py-spy to see inside containers from the host, crack four production puzzles (connection pools, timeout chains, private DNS, SNAT), tune performance and cost with cgroup evidence, fill in build at scale, advanced networking, developer experience and GPUs, and finish with a blind box of 8 faults
Engine 29.10 · buildx 0.39 · BuildKit 0.35py-spy 0.4.3 · netshoot v0.16 · k6 2.4Testcontainers 4.15 · Dev Containers CLI 0.90 · NVIDIA CTK 1.208 reproducible faultsVerified against official docs · 2026-11-17
Overall learning objectives
  • Build a layered troubleshooting mindset: save the evidence first, then locate the layer in the order "application → process → container → network → host → cloud platform"; use USE for resources and RED for services.
  • Without changing the image or opening a shell in the container, use nsenter, a netshoot container sharing its namespaces, docker debug, tcpdump, strace and py-spy to observe a container's network, system calls and Python call stacks.
  • Independently diagnose the four most common production puzzles: connection pool exhaustion, 502/504 and timeout chains, private-network DNS, SNAT/source port exhaustion, and design a timeout hierarchy where "the inner layer times out first".
  • Tune performance with cgroup evidence (cpu.stat throttling, PSI) and k6 P95/P99; set concurrency from the CPU quota, not the host's core count; estimate cost in vCPU-seconds / GiB-seconds.
  • Build at scale: choose a builder driver, connect to remote BuildKit (mTLS) or Build Cloud, make reproducible builds with SOURCE_DATE_EPOCH and verify the digest, and build several variants with a Bake matrix.
  • Master macvlan / ipvlan (and their limits in the cloud), IPv6 dual stack, the experimental nftables backend in Engine 29, MTU and storage performance; improve developer experience with Dev Containers and Testcontainers; understand GPU containers (NVIDIA Container Toolkit, --gpus, CDI).
  • In a 10-minute "fault blind box", find the injected fault from symptoms alone and state the complete chain of evidence.

1-hour schedule

#TimeModuleCore contentAnimation / interactionLab
0Before classSetup: fault injection & diagnostic toolsUpgrade orders (chaos/, perf/, tests/, .devcontainer/, Bake); install strace, tcpdump, py-spy; pull netshoot and k6; record a baselineEnvironment self-check listEnable /api/chaos/*, save the baseline
100–05Troubleshooting methodology & toolboxCollect evidence before you mitigate, the six-layer model, USE / RED, tool map, evidence checklistEvidence collection during an incident (five failures)One-command evidence collection before restarting
205–13Process- and syscall-level troubleshooting ⭐nsenter, --network/--pid container:, netshoot, docker debug, tcpdump, strace, py-spy"From symptom to line of code" tool-attach simulation (six failures)See connections, call stacks, system calls and handshakes without changing the image
313–21Connections & timeout chains ⭐Connection pool exhaustion, 502/504 and the timeout hierarchy, private DNS (getent vs dig), SNAT / source port exhaustionA request through five layers of timeouts + timeout hierarchy sliderInject and diagnose 4 faults one by one (several measured)
421–29Performance & cost optimizationCFS quota and throttling, PSI, gunicorn processes/threads, k6 P95/P99, Little's law, cold starts, vCPU-seconds / GiB-secondsCFS throttling canvas (preset scenarios) + cost calculatorLoad test → spot throttling → tune → compare
529–36Build at scaleBuilder drivers, remote BuildKit (mTLS) / Build Cloud, build records, reproducible builds (SOURCE_DATE_EPOCH, rewrite-timestamp), Bake matricesTwo-build digest comparator (six failures)Bake matrix + digest comparison + remote builder
636–43Advanced networking & storagemacvlan / ipvlan (cloud limits), IPv6 dual stack, nftables backend (experimental), MTU, volume / bind mount / tmpfs performancePacket path simulation (seven scenarios)macvlan/ipvlan on a dummy NIC, IPv6, nftables, dd comparison
743–50Developer experience + GPU / AIDev Containers, Testcontainers (4.x import paths), NVIDIA Container Toolkit, --gpus and CDIThe startup path from tests to GPUs (six failures)Testcontainers integration tests, Dev Container CLI, GPU (optional)
850–60Fault blind box + seven-hour recap8 random faults, chains of evidence, seven-hour knowledge map, interactive troubleshooting tree, next stepsBlind box simulator (scored) + troubleshooting treechaos/blindbox.sh, three rounds
—After classCheat sheet · Capstone labPerformance baseline → two rounds of tuning → fix connection reuse in publish() → timeout hierarchy → optimization reportFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commands / objectsLab
Evidence collection and layer isolation✓✓✓✓·✓·✓docker inspect/events/logs, USE / REDM1 / M8
Namespaces and debug containers✓✓✓··✓·✓nsenter, --network container:, netshoot, docker debugM2
System calls and call stacks·✓✓✓···✓strace -f -tt -T, py-spy dump/top/recordM2 / M3
Connections, timeouts and DNS·✓✓··✓·✓ss, tcpdump, getent hosts, digM3
CPU throttling, PSI and load testing✓··✓···✓cpu.max, cpu.stat, *.pressure, k6M4
Cost model···✓✓·✓·vCPU-seconds, GiB-seconds, minimum replicasM4 calculator
Build at scale and reproducibility····✓·✓✓buildx create --driver, SOURCE_DATE_EPOCH, bake --printM5
Advanced networking and storage··✓··✓·✓macvlan / ipvlan, --ipv6, firewall-backend, MTU, tmpfsM6
Developer experience and GPUs····✓·✓·devcontainer up, Testcontainers, nvidia-ctk, CDIM7

What this hour leaves out (and where to learn it)

TopicWhy it is not in this hourWhere to learn it
BuildKit cache backends (registry / gha / local), mode=max, ECR cache parameters, multi-platform, Bake basics, SBOM and signingAlready covered in hour 5 as part of image CI; Module 5 of this hour only covers the scale-out part (drivers, remote builders, reproducibility, matrices)Hour 5 Module 2 · Module 5 · Module 6
General Linux performance tools (vmstat, iostat, perf, eBPF/bpftrace) and the USE 60-second analysisThat is Linux host troubleshooting; this hour focuses on the "container view"Linux hour 7 · Module 1 (Chinese) · Module 7: strace, perf, eBPF (Chinese)
Kernel internals of namespaces and cgroups, nftables rule syntaxUsed directly in this hourLinux hour 6 · Module 7 (Chinese) · Module 3: nftables (Chinese)
Metrics collection, alert rules, dashboards and SLOsThis hour only uses one-off commands to collect evidencePrometheus & Grafana in 8 hours (Chinese)
The same kind of troubleshooting in Kubernetes (kubectl debug, ephemeral containers, node-pressure eviction)That belongs to the orchestration platformKubernetes hour 6 · Module 3 (Chinese) · Module 8: master troubleshooting decision tree (Chinese)
Architecture of orders, its connection budget and database migrationsCovered in hour 6; this hour injects faults on top of itHour 6 Module 2 · Module 5

How to use this courseware

10 tabs per module
Concepts · Diagram · Animation · Commands · Lab · In Production · Troubleshooting · Quiz · Audio · Video. Every animation includes "failure branches": pick a failure scenario first to see at which step it stops and what appears in the terminal, then go to the "Troubleshooting" tab to compare with the real error.
Progress
A quiz score ≥ 70% or clicking "Mark this module complete" counts toward progress. It is saved in this browser (shared with the course index under one progress key; if local storage is blocked it is cleared on refresh).
English audio
The "Audio" tab reads the scripts aloud with the browser's built-in Web Speech API (en-US); without an English voice the scripts can still be read or fed to a TTS tool.
How this relates to the first six hoursWhat a container really is (namespaces, cgroups, runc) is in Hour 1; resource limits, exit codes and health checks are in Hour 2; Container Apps and KQL are in Hour 3; image CI, cache backends and the supply chain are in Hour 5; the orders system and its connection budget are in Hour 6. This is the last core hour of the Docker track: Hour 8 is the optional "50 production problems + 50 interview questions", after which you move on to Kubernetes in 8 hours (Chinese).
Environment and costsThe main labs run on one Ubuntu 24.04 VM (2 vCPU / 4 GiB recommended, cgroup v2) and incur no cloud costs. The Azure comparisons in Modules 3 / 4 only give commands and KQL; the GPU lab needs a VM with an NVIDIA GPU (for example the Azure NC series, which is expensive) and is marked optional. Output labeled "measured" comes from a process-level environment configured the same way as the containers; all other output is illustrative, see Sources & version notes.

Module 0 · Setup: fault injection & diagnostic tools (before class)

Layer chaos/ fault injection, k6 load tests, Testcontainers tests and a Bake file on top of the orders project from hour 6, and install the host-side diagnostic tools
Before class ≈ 15 minOne Ubuntu 24.04 VM is enoughRequires sudo
Prerequisites
  • You have completed Hour 6 and ~/orders runs fine with docker compose up -d (if not, the script below can generate all 48 files directly).
  • Lab machine: the Ubuntu 24.04 VM from hour 1 (2 vCPU / 4 GiB recommended, cgroup v2), Docker Engine 29.x (the latest at the time of verification is 29.10.0) and the Compose plugin.
  • sudo on the VM: nsenter, tcpdump, strace and py-spy all need root to observe container processes.
  • Optional: a VM with an NVIDIA GPU (the GPU lab in Module 7) and an extra Linux machine as a remote builder (Module 5). You can finish the main track of this hour without them.

1. Upgrade the orders project

The new generator script (48 files) adds, on top of hour 6, chaos/ (fault injection), perf/ (k6), app/tests/ (Testcontainers), .devcontainer/ and docker-bake.hcl, and adds /api/chaos/* endpoints to the API that are registered only when CHAOS_ENABLED=1. An existing .env is not overwritten.

orders-bootstrap.sh full text (hour 7 version, click to expand)
#!/usr/bin/env bash
# Generator for the complete orders sample project (Hours 5–6): bash orders-bootstrap.sh  → creates ~/orders
set -euo pipefail
D=${1:-$HOME/orders}; mkdir -p "$D"; cd "$D"
cat > .env.example <<'ORDERS_EOF'
# Copy to .env and change the passwords; never commit .env to Git
DB_PASSWORD=change-me-db
MQ_PASSWORD=change-me-mq
# Azurite's public development account (a fixed key published in the docs; local use only)
AZURITE_CONN=DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://azurite:10000/devstoreaccount1;
ORDERS_EOF
cat > .gitignore <<'ORDERS_EOF'
.env
gateway/certs/
__pycache__/
chaos/.state
chaos/.nginx-f3.conf
ORDERS_EOF
cat > README.md <<'ORDERS_EOF'
# orders — sample project for Docker hour 6

Order system: SPA + nginx gateway (HTTPS/rate limiting) + Flask API (connection pool, cache-aside, idempotency keys)
+ PostgreSQL + Redis + RabbitMQ worker (retries/dead-lettering/graceful shutdown) + migration job + scheduled report + Azurite (Blob + SAS).

```bash
cp .env.example .env            # change the passwords
./gen-cert.sh                   # self-signed certificate
docker compose up -d --build    # https://localhost:8443
docker compose run --rm report  # scheduled job (run manually)
bash azure/deploy.sh            # deploy to Azure (paid resources; az group delete when done)
```

Course: docker-h6.html

## Added in hour 7 (deep troubleshooting and optimization)
- `chaos/`: fault injection (base.yaml enables the `/api/chaos/*` endpoints; f1–f8 eight faults; traffic.sh mixed traffic; blindbox.sh blind box)
- `perf/load.js`: k6 load test; `docker-bake.hcl`: Bake matrix + SOURCE_DATE_EPOCH
- `.devcontainer/`: Dev Containers; `app/tests/`: Testcontainers integration tests
```bash
docker compose -f compose.yaml -f chaos/base.yaml up -d   # enable the fault-injection endpoints
bash chaos/blindbox.sh start                             # draw a random fault
```
ORDERS_EOF
cat > compose.yaml <<'ORDERS_EOF'
name: orders

x-app: &app
  image: orders:1.0
  build: ./app
  environment: &app-env
    DATABASE_URL: postgresql://orders:${DB_PASSWORD:?run cp .env.example .env}@postgres:5432/orders
    REDIS_URL: redis://redis:6379/0
    QUEUE_BACKEND: rabbitmq
    RABBITMQ_URL: amqp://orders:${MQ_PASSWORD:?run cp .env.example .env}@rabbitmq:5672/
    STORAGE_CONNECTION_STRING: ${AZURITE_CONN}
    BLOB_PUBLIC_BASE: https://localhost:8443/blob
    APP_VERSION: "1.0"
  restart: unless-stopped
  stop_grace_period: 30s

services:
  migrate:                       # one-off job: api / worker start only after a successful migration
    <<: *app
    command: ["orders-migrate"]
    restart: "no"
    depends_on:
      postgres: { condition: service_healthy }

  api:
    <<: *app
    depends_on:
      migrate:  { condition: service_completed_successfully }
      redis:    { condition: service_healthy }
      rabbitmq: { condition: service_healthy }
      azurite:  { condition: service_started }
    deploy:
      replicas: 2
      resources: { limits: { cpus: "0.5", memory: 256M } }

  worker:
    <<: *app
    command: ["orders-worker"]
    healthcheck: { disable: true }
    depends_on:
      migrate:  { condition: service_completed_successfully }
      rabbitmq: { condition: service_healthy }
    deploy:
      replicas: 2

  report:                        # scheduled job: docker compose run --rm report (triggered by host cron / an ACA Job)
    <<: *app
    command: ["orders-report"]
    restart: "no"
    healthcheck: { disable: true }
    profiles: [jobs]
    depends_on:
      postgres: { condition: service_healthy }

  gateway:
    image: nginx:1.29-alpine
    ports: ["8443:443", "8080:80"]
    volumes:
      - ./gateway/nginx.conf:/etc/nginx/conf.d/default.conf:ro
      - ./gateway/certs:/etc/nginx/certs:ro
      - ./web:/usr/share/nginx/html:ro
    depends_on: [api]
    restart: unless-stopped

  postgres:
    image: postgres:17
    environment:
      POSTGRES_USER: orders
      POSTGRES_PASSWORD: ${DB_PASSWORD:?run cp .env.example .env}
      POSTGRES_DB: orders
    volumes: [pgdata:/var/lib/postgresql/data]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U orders -d orders"]
      interval: 5s
      timeout: 3s
      retries: 10
    restart: unless-stopped

  redis:
    image: redis:7-alpine
    command: ["redis-server", "--appendonly", "yes", "--maxmemory", "128mb", "--maxmemory-policy", "allkeys-lru"]
    volumes: [redisdata:/data]
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      retries: 10
    restart: unless-stopped

  rabbitmq:
    image: rabbitmq:4-management
    environment:
      RABBITMQ_DEFAULT_USER: orders
      RABBITMQ_DEFAULT_PASS: ${MQ_PASSWORD:?run cp .env.example .env}
    ports: ["127.0.0.1:15672:15672"]          # management UI bound to localhost only
    volumes: [mqdata:/var/lib/rabbitmq]
    healthcheck:
      test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
      interval: 10s
      timeout: 5s
      retries: 12
    restart: unless-stopped

  azurite:
    image: mcr.microsoft.com/azure-storage/azurite
    command: ["azurite-blob", "--blobHost", "0.0.0.0", "--location", "/data", "--skipApiVersionCheck"]
    volumes: [blobdata:/data]
    restart: unless-stopped

volumes:
  pgdata:
  redisdata:
  mqdata:
  blobdata:
ORDERS_EOF
cat > docker-bake.hcl <<'ORDERS_EOF'
# hour 7: Bake matrix + reproducible builds. docker buildx bake --print shows the expansion
variable "TAG" { default = "dev" }
variable "SOURCE_DATE_EPOCH" { default = "0" }   # in CI set to $(git log -1 --pretty=%ct)

group "default" { targets = ["app", "web"] }

target "_common" {
  args      = { SOURCE_DATE_EPOCH = SOURCE_DATE_EPOCH }
  platforms = ["linux/amd64"]
  labels    = { "org.opencontainers.image.source" = "https://github.com/yourname/orders" }
}

target "app" {
  inherits = ["_common"]
  name     = "app-py${replace(py, ".", "")}"
  matrix   = { py = ["3.12", "3.13"] }
  context  = "app"
  args     = { PYTHON_VERSION = py }
  tags     = ["orders:${TAG}-py${py}"]
}

target "web" {
  inherits = ["_common"]
  context  = "web"
  tags     = ["orders-web:${TAG}"]
}
ORDERS_EOF
cat > gen-cert.sh <<'ORDERS_EOF'
#!/usr/bin/env bash
# Generate a local self-signed certificate (development only; in production use ACA managed certificates / Let's Encrypt / Key Vault certificates)
set -euo pipefail
mkdir -p gateway/certs
openssl req -x509 -newkey rsa:2048 -nodes -days 30 \
  -keyout gateway/certs/tls.key -out gateway/certs/tls.crt \
  -subj "/CN=localhost" -addext "subjectAltName=DNS:localhost,IP:127.0.0.1"
chmod 644 gateway/certs/tls.key   # read by the nginx master as root in the container; don't do this in production
echo "Certificate generated: gateway/certs/"
ORDERS_EOF
mkdir -p .devcontainer
cat > .devcontainer/compose.devcontainer.yaml <<'ORDERS_EOF'
services:
  dev:
    image: mcr.microsoft.com/devcontainers/python:3.13
    volumes:
      - ..:/workspaces/orders:cached
    command: sleep infinity          # keep running; VS Code attaches to it
    environment:
      DATABASE_URL: postgresql://orders:${DB_PASSWORD}@postgres:5432/orders
      REDIS_URL: redis://redis:6379/0
      QUEUE_BACKEND: rabbitmq
      RABBITMQ_URL: amqp://orders:${MQ_PASSWORD}@rabbitmq:5672/
      STORAGE_CONNECTION_STRING: ${AZURITE_CONN}
      CHAOS_ENABLED: "1"
ORDERS_EOF
mkdir -p .devcontainer
cat > .devcontainer/devcontainer.json <<'ORDERS_EOF'
{
  // hour 7: VS Code "Reopen in Container" / GitHub Codespaces. Reuses the dependency services from compose.yaml
  "name": "orders-dev",
  "dockerComposeFile": ["../compose.yaml", "compose.devcontainer.yaml"],
  "service": "dev",
  "runServices": ["dev", "postgres", "redis", "rabbitmq", "azurite"],
  "workspaceFolder": "/workspaces/orders",
  "shutdownAction": "stopCompose",
  "features": {
    "ghcr.io/devcontainers/features/docker-outside-of-docker:1": {}
  },
  "forwardPorts": [8000, 15672],
  "postCreateCommand": "pip install --user -r app/requirements-dev.txt",
  "customizations": {
    "vscode": { "extensions": ["ms-python.python", "ms-azuretools.vscode-containers"] }
  }
}
ORDERS_EOF
mkdir -p app
cat > app/.dockerignore <<'ORDERS_EOF'
__pycache__
*.pyc
.git
migrations-contract
tests
requirements-dev.txt
ORDERS_EOF
mkdir -p app
cat > app/Dockerfile <<'ORDERS_EOF'
# syntax=docker/dockerfile:1
# check=error=true
ARG PYTHON_VERSION=3.13

FROM python:${PYTHON_VERSION}-slim AS builder
# hour 7: reproducible build. Once declared it is visible in RUN; py_compile switches to hash-based .pyc
ARG SOURCE_DATE_EPOCH
ENV PIP_DISABLE_PIP_VERSION_CHECK=1
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt

FROM python:${PYTHON_VERSION}-slim AS runtime
LABEL org.opencontainers.image.source="https://github.com/yourname/orders" \
      org.opencontainers.image.title="orders"
RUN useradd --uid 10001 --create-home app
WORKDIR /app
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH" PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
COPY --chown=10001:10001 orders ./orders
COPY --chown=10001:10001 migrations ./migrations
COPY --chmod=755 bin/ /usr/local/bin/
USER 10001:10001
EXPOSE 8000
HEALTHCHECK --interval=15s --timeout=3s --start-period=10s --start-interval=1s --retries=3 \
  CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2)"]
# One image, several process types (12-Factor): api (default), orders-worker, orders-migrate, orders-report
CMD ["gunicorn", "-b", "0.0.0.0:8000", "-w", "2", "--graceful-timeout", "20", "--access-logfile", "-", "orders.api:app"]
ORDERS_EOF
mkdir -p app
cat > app/requirements-dev.txt <<'ORDERS_EOF'
-r requirements.txt
pytest==8.*
testcontainers[postgres]==4.*
ORDERS_EOF
mkdir -p app
cat > app/requirements.txt <<'ORDERS_EOF'
flask==3.1.*
gunicorn==23.*
psycopg[binary]==3.2.*
psycopg-pool==3.2.*
redis==5.*
pika==1.3.*
azure-storage-blob==12.*
azure-identity==1.*
azure-servicebus==7.*
ORDERS_EOF
mkdir -p app/bin
cat > app/bin/orders-migrate <<'ORDERS_EOF'
#!/bin/sh
exec python -m orders.migrate "$@"
ORDERS_EOF
mkdir -p app/bin
cat > app/bin/orders-report <<'ORDERS_EOF'
#!/bin/sh
exec python -m orders.report "$@"
ORDERS_EOF
mkdir -p app/bin
cat > app/bin/orders-worker <<'ORDERS_EOF'
#!/bin/sh
exec python -m orders.worker "$@"
ORDERS_EOF
mkdir -p app/migrations
cat > app/migrations/001_init.sql <<'ORDERS_EOF'
CREATE TABLE IF NOT EXISTS orders (
    id              bigserial PRIMARY KEY,
    item            text        NOT NULL,
    qty             integer     NOT NULL CHECK (qty > 0),
    status          text        NOT NULL DEFAULT 'pending',
    idempotency_key text        UNIQUE,
    created_at      timestamptz NOT NULL DEFAULT now(),
    processed_at    timestamptz
);
CREATE TABLE IF NOT EXISTS daily_reports (
    day          date PRIMARY KEY,
    orders       integer NOT NULL,
    items        integer NOT NULL,
    generated_at timestamptz NOT NULL
);
ORDERS_EOF
mkdir -p app/migrations
cat > app/migrations/002_expand_customer_email.sql <<'ORDERS_EOF'
-- Expand phase: only add nullable columns, so the old app version is unaffected
ALTER TABLE orders ADD COLUMN IF NOT EXISTS customer_email text;
CREATE INDEX IF NOT EXISTS ix_orders_created_at ON orders (created_at);
ORDERS_EOF
mkdir -p app/migrations-contract
cat > app/migrations-contract/003_contract_customer_email.sql <<'ORDERS_EOF'
-- Contract phase: move this into migrations/ only after confirming every running version writes customer_email
UPDATE orders SET customer_email = 'unknown@example.com' WHERE customer_email IS NULL;
ALTER TABLE orders ALTER COLUMN customer_email SET NOT NULL;
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/__init__.py <<'ORDERS_EOF'

ORDERS_EOF
mkdir -p app/orders
cat > app/orders/api.py <<'ORDERS_EOF'
"""Orders API: cache-aside, idempotent creation, async processing, file uploads."""
import json, os, socket, uuid
from flask import Flask, jsonify, request, abort
import psycopg
import redis as redislib
from . import config, db, queueing, storage
from .log import get_logger, info

log = get_logger("api")
app = Flask(__name__)
cache = redislib.Redis.from_url(config.REDIS_URL, socket_timeout=0.5, socket_connect_timeout=0.5)
db.ensure_open()
if config.CHAOS_ENABLED:                 # hour 7: register fault-injection endpoints only in lab environments
    from .chaos import bp as chaos_bp
    app.register_blueprint(chaos_bp)

def cache_get(key):
    try:
        v = cache.get(key)
        return json.loads(v) if v else None
    except redislib.RedisError:
        log.warning("cache unavailable, falling back to database")   # a cache failure must not affect correctness
        return None

def cache_set(key, value, ttl=config.CACHE_TTL):
    try:
        cache.setex(key, ttl, json.dumps(value, default=str))
    except redislib.RedisError:
        pass

def cache_del(*keys):
    try:
        cache.delete(*keys)
    except redislib.RedisError:
        pass

@app.get("/healthz")
def healthz():                       # liveness: checks only the process itself
    return "ok"

@app.get("/readyz")
def readyz():
    """Readiness: accept traffic only when dependencies are available. Uses a separate short-lived connection + connect_timeout
    so the probe never hangs on a pooled connection when the database stops responding (the pool timeout covers borrowing a connection, not queries)."""
    try:
        with psycopg.connect(config.DATABASE_URL, connect_timeout=2) as conn:
            conn.execute("SELECT 1")
    except Exception as e:
        log.warning("not ready: %s", e)
        return "database unavailable", 503
    return "ready"

@app.post("/api/orders")
def create_order():
    body = request.get_json(silent=True) or {}
    item, qty = body.get("item"), body.get("qty")
    if not item or not isinstance(qty, int) or qty <= 0:
        abort(400, "item and a positive integer qty are required")
    key = request.headers.get("Idempotency-Key") or str(uuid.uuid4())
    with db.pool.connection() as conn:
        row = conn.execute(
            """INSERT INTO orders (item, qty, customer_email, idempotency_key)
               VALUES (%s, %s, %s, %s)
               ON CONFLICT (idempotency_key) DO NOTHING
               RETURNING id, status""",
            (item, qty, body.get("email"), key)).fetchone()
        created = row is not None
        if not created:     # client retry: return the order created the first time, never create a duplicate
            row = conn.execute("SELECT id, status FROM orders WHERE idempotency_key=%s", (key,)).fetchone()
    if created:
        queueing.publish({"order_id": row["id"]})   # in production, the outbox pattern keeps the DB write and the message consistent
        cache_del("stats")
    info(log, "order accepted", order_id=row["id"], created=created)
    return jsonify(id=row["id"], status=row["status"], created=created), 202 if created else 200

@app.get("/api/orders/<int:order_id>")
def get_order(order_id):
    key = f"order:{order_id}"
    hit = cache_get(key)
    if hit:
        return jsonify(hit | {"cache": "hit"})
    with db.pool.connection() as conn:
        row = conn.execute("SELECT * FROM orders WHERE id=%s", (order_id,)).fetchone()
    if not row:
        abort(404)
    if row["status"] != "pending":           # cache only stable data; pending orders still change status
        cache_set(key, row)
    return jsonify(row | {"cache": "miss"})

@app.get("/api/orders")
def list_orders():
    with db.pool.connection() as conn:
        rows = conn.execute("SELECT id, item, qty, status, created_at FROM orders ORDER BY id DESC LIMIT 20").fetchall()
    return jsonify(rows)

@app.get("/api/stats")
def stats():
    hit = cache_get("stats")
    if hit:
        return jsonify(hit | {"cache": "hit", "served_by": socket.gethostname(), "version": config.APP_VERSION})
    with db.pool.connection() as conn:
        row = conn.execute("""SELECT count(*) AS orders, coalesce(sum(qty),0) AS items,
                              count(*) FILTER (WHERE status='processed') AS processed FROM orders""").fetchone()
    cache_set("stats", row, ttl=10)
    return jsonify(row | {"cache": "miss", "served_by": socket.gethostname(), "version": config.APP_VERSION})

@app.post("/api/files")
def upload_file():
    f = request.files.get("file")
    if not f:
        abort(400, "missing file")
    name = f"{uuid.uuid4().hex}-{os.path.basename(f.filename or 'upload.bin')}"
    storage.upload(name, f.stream, f.mimetype or "application/octet-stream")
    info(log, "file uploaded", blob=name)
    return jsonify(name=name, url=storage.download_url(name)), 201

@app.get("/api/files/<name>/url")
def file_url(name):
    return jsonify(url=storage.download_url(name))
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/chaos.py <<'ORDERS_EOF'
"""hour 7: fault-injection endpoints (registered only when CHAOS_ENABLED=1). Reproduce slow requests, slow queries, memory leaks and busy CPU."""
import time
from flask import Blueprint, jsonify, request
from . import db

bp = Blueprint("chaos", __name__, url_prefix="/api/chaos")
_leak = []

@bp.get("/sleep")
def sleep():                     # slow application: holds one gunicorn worker
    s = float(request.args.get("s", 5))
    time.sleep(s)
    return jsonify(slept=s)

@bp.get("/dbsleep")
def dbsleep():                   # slow database: holds one pool connection (bounded by statement_timeout)
    s = float(request.args.get("s", 3))
    with db.pool.connection() as conn:
        conn.execute("SELECT pg_sleep(%s)", (s,))
    return jsonify(db_slept=s)

@bp.get("/cpu")
def cpu():                       # busy CPU: pure computation for ms milliseconds
    ms = float(request.args.get("ms", 200)); end = time.perf_counter() + ms / 1000; n = 0
    while time.perf_counter() < end:
        n += 1
    return jsonify(loops=n)

@bp.get("/leak")
def leak():                      # memory leak: retains mb MB per call
    mb = int(request.args.get("mb", 10))
    _leak.append(bytearray(mb * 1024 * 1024))
    return jsonify(leaked_mb=sum(len(b) for b in _leak) // 2**20)
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/config.py <<'ORDERS_EOF'
"""12-Factor: all configuration comes from environment variables."""
import os

DATABASE_URL = os.environ.get("DATABASE_URL", "postgresql://orders:orders@localhost:5432/orders")
DB_POOL_SIZE = int(os.getenv("DB_POOL_SIZE", "5"))
REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0")
CACHE_TTL = int(os.getenv("CACHE_TTL", "60"))

QUEUE_BACKEND = os.getenv("QUEUE_BACKEND", "none")          # rabbitmq | servicebus | none
QUEUE_NAME = os.getenv("QUEUE_NAME", "orders")
RABBITMQ_URL = os.getenv("RABBITMQ_URL", "amqp://guest:guest@localhost:5672/")
SERVICEBUS_NAMESPACE = os.getenv("SERVICEBUS_NAMESPACE", "")  # <ns>.servicebus.windows.net
MAX_RETRIES = int(os.getenv("MAX_RETRIES", "3"))

STORAGE_CONNECTION_STRING = os.getenv("STORAGE_CONNECTION_STRING", "")  # local Azurite
STORAGE_ACCOUNT_URL = os.getenv("STORAGE_ACCOUNT_URL", "")              # Azure: https://<acct>.blob.core.windows.net
BLOB_CONTAINER = os.getenv("BLOB_CONTAINER", "files")
BLOB_PUBLIC_BASE = os.getenv("BLOB_PUBLIC_BASE", "")                    # rewrites URLs when Azurite is reached through the local gateway
APP_VERSION = os.getenv("APP_VERSION", "dev")
DB_POOL_TIMEOUT = float(os.getenv("DB_POOL_TIMEOUT", "30"))       # max wait to borrow a connection (seconds)
CHAOS_ENABLED = os.getenv("CHAOS_ENABLED", "0") == "1"           # hour 7: fault-injection endpoints; must be off in production
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/db.py <<'ORDERS_EOF'
"""Database connection pool: one pool per process; pool size × processes × replicas must stay below the database max_connections."""
from psycopg_pool import ConnectionPool
from psycopg.rows import dict_row
from . import config

pool = ConnectionPool(config.DATABASE_URL, min_size=1, max_size=config.DB_POOL_SIZE,
                      timeout=config.DB_POOL_TIMEOUT,
                      kwargs={"row_factory": dict_row,
                              "options": "-c statement_timeout=5000"},   # server side: max 5 seconds per statement
                      open=False)

def ensure_open():
    if pool.closed:
        pool.open(wait=True, timeout=10)
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/log.py <<'ORDERS_EOF'
"""Structured (JSON) logging to stdout."""
import json, logging, sys, time

class JsonFormatter(logging.Formatter):
    def format(self, record):
        d = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S%z"), "level": record.levelname,
             "logger": record.name, "msg": record.getMessage()}
        d.update(getattr(record, "extra_fields", {}))
        if record.exc_info:
            d["exc"] = self.formatException(record.exc_info)
        return json.dumps(d, ensure_ascii=False)

def get_logger(name):
    log = logging.getLogger(name)
    if not log.handlers:
        h = logging.StreamHandler(sys.stdout)
        h.setFormatter(JsonFormatter())
        log.addHandler(h)
        log.setLevel(logging.INFO)
        log.propagate = False
    return log

def info(log, msg, **fields):
    log.info(msg, extra={"extra_fields": fields})
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/migrate.py <<'ORDERS_EOF'
"""Minimal migration tool: runs migrations/*.sql in filename order, one transaction per file;
a PostgreSQL advisory lock ensures only one replica migrates when several start at once. In production use Alembic / Flyway."""
import glob, os, sys
import psycopg
from . import config
from .log import get_logger, info

log = get_logger("migrate")
LOCK_ID = 727274
DIR = os.getenv("MIGRATIONS_DIR", os.path.join(os.path.dirname(__file__), "..", "migrations"))

def main():
    with psycopg.connect(config.DATABASE_URL, autocommit=True) as conn:
        conn.execute("SELECT pg_advisory_lock(%s)", (LOCK_ID,))
        try:
            conn.execute("""CREATE TABLE IF NOT EXISTS schema_migrations
                            (version text PRIMARY KEY, applied_at timestamptz DEFAULT now())""")
            done = {r[0] for r in conn.execute("SELECT version FROM schema_migrations")}
            for path in sorted(glob.glob(os.path.join(DIR, "*.sql"))):
                ver = os.path.basename(path)
                if ver in done:
                    continue
                with conn.transaction():
                    conn.execute(open(path, encoding="utf-8").read())
                    conn.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (ver,))
                info(log, "applied", version=ver)
            info(log, "up to date", applied=len(done))
        finally:
            conn.execute("SELECT pg_advisory_unlock(%s)", (LOCK_ID,))

if __name__ == "__main__":
    sys.exit(main())
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/queueing.py <<'ORDERS_EOF'
"""Message queue abstraction: RabbitMQ locally, Service Bus on Azure; business code never sees the difference."""
import json, signal
from . import config
from .log import get_logger, info

log = get_logger("queue")

# ---------------- RabbitMQ ----------------
def _rabbit_channel():
    import pika
    conn = pika.BlockingConnection(pika.URLParameters(config.RABBITMQ_URL))
    ch = conn.channel()
    # dead-lettering: messages that exceed the retry count go to orders.dlq
    ch.exchange_declare("orders.dlx", "fanout", durable=True)
    ch.queue_declare(f"{config.QUEUE_NAME}.dlq", durable=True)
    ch.queue_bind(f"{config.QUEUE_NAME}.dlq", "orders.dlx")
    ch.queue_declare(config.QUEUE_NAME, durable=True,
                     arguments={"x-dead-letter-exchange": "orders.dlx"})
    return conn, ch

def publish(message: dict):
    body = json.dumps(message)
    if config.QUEUE_BACKEND == "rabbitmq":
        import pika
        conn, ch = _rabbit_channel()
        try:
            ch.basic_publish("", config.QUEUE_NAME, body,
                             pika.BasicProperties(delivery_mode=2, content_type="application/json"))
        finally:
            conn.close()
    elif config.QUEUE_BACKEND == "servicebus":
        from azure.identity import DefaultAzureCredential
        from azure.servicebus import ServiceBusClient, ServiceBusMessage
        with ServiceBusClient(config.SERVICEBUS_NAMESPACE, DefaultAzureCredential()) as sb:
            with sb.get_queue_sender(config.QUEUE_NAME) as sender:
                sender.send_messages(ServiceBusMessage(body, content_type="application/json"))
    info(log, "published", backend=config.QUEUE_BACKEND, message=message)

def consume(handler):
    """handler(dict) raising an exception means processing failed. On SIGTERM, finish the current message and then exit (graceful shutdown)."""
    stopping = {"flag": False}
    def _stop(signum, frame):
        stopping["flag"] = True
        info(log, "SIGTERM received, finishing current message")
    signal.signal(signal.SIGTERM, _stop)

    if config.QUEUE_BACKEND == "rabbitmq":
        import pika
        conn, ch = _rabbit_channel()
        ch.basic_qos(prefetch_count=1)
        for method, props, body in ch.consume(config.QUEUE_NAME, inactivity_timeout=1):
            if stopping["flag"]:
                break
            if method is None:
                continue
            retries = int((props.headers or {}).get("x-retry", 0))
            try:
                handler(json.loads(body))
                ch.basic_ack(method.delivery_tag)            # ack only after successful processing
            except Exception:
                log.exception("handler failed")
                if retries + 1 >= config.MAX_RETRIES:
                    ch.basic_nack(method.delivery_tag, requeue=False)   # → dead-letter queue
                    info(log, "dead-lettered", retries=retries + 1)
                else:
                    ch.basic_publish("", config.QUEUE_NAME, body, pika.BasicProperties(
                        delivery_mode=2, headers={"x-retry": retries + 1}))
                    ch.basic_ack(method.delivery_tag)
        ch.cancel(); conn.close()
    elif config.QUEUE_BACKEND == "servicebus":
        from azure.identity import DefaultAzureCredential
        from azure.servicebus import ServiceBusClient
        with ServiceBusClient(config.SERVICEBUS_NAMESPACE, DefaultAzureCredential()) as sb:
            with sb.get_queue_receiver(config.QUEUE_NAME, max_wait_time=5) as receiver:
                while not stopping["flag"]:
                    for msg in receiver.receive_messages(max_message_count=1, max_wait_time=5):
                        try:
                            handler(json.loads(str(msg)))
                            receiver.complete_message(msg)
                        except Exception:
                            log.exception("handler failed")
                            # after abandon, Service Bus redelivers automatically; beyond MaxDeliveryCount it goes to the dead-letter subqueue
                            receiver.abandon_message(msg)
    else:
        raise SystemExit("QUEUE_BACKEND=none: no queue to consume")
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/report.py <<'ORDERS_EOF'
"""Scheduled job: builds the daily order report for a given day (written to the database and uploaded as CSV). Safe to rerun (idempotent upsert)."""
import csv, io, os, sys
from datetime import date, timedelta
from . import db, storage
from .log import get_logger, info

log = get_logger("report")

def main():
    day = date.fromisoformat(os.getenv("REPORT_DAY")) if os.getenv("REPORT_DAY") else date.today() - timedelta(days=1)
    db.ensure_open()
    with db.pool.connection() as conn:
        rows = conn.execute("""SELECT item, count(*) AS orders, sum(qty) AS items FROM orders
                               WHERE created_at::date = %s GROUP BY item ORDER BY item""", (day,)).fetchall()
        total_o = sum(r["orders"] for r in rows); total_i = sum(r["items"] for r in rows)
        conn.execute("""INSERT INTO daily_reports (day, orders, items, generated_at) VALUES (%s,%s,%s,now())
                        ON CONFLICT (day) DO UPDATE SET orders=EXCLUDED.orders, items=EXCLUDED.items,
                        generated_at=now()""", (day, total_o, total_i))
    buf = io.StringIO(); w = csv.writer(buf); w.writerow(["item", "orders", "items"])
    for r in rows:
        w.writerow([r["item"], r["orders"], r["items"]])
    name = f"reports/{day.isoformat()}.csv"
    storage.container().upload_blob(name, buf.getvalue().encode(), overwrite=True)
    info(log, "report generated", day=str(day), orders=total_o, blob=name)
    db.pool.close()

if __name__ == "__main__":
    sys.exit(main())
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/storage.py <<'ORDERS_EOF'
"""Object storage: Azurite locally (connection string), Blob Storage + managed identity on Azure (user delegation SAS)."""
from datetime import datetime, timedelta, timezone
from azure.storage.blob import (BlobServiceClient, BlobSasPermissions, generate_blob_sas)
from . import config

_client = None

def client() -> BlobServiceClient:
    global _client
    if _client is None:
        if config.STORAGE_CONNECTION_STRING:
            _client = BlobServiceClient.from_connection_string(config.STORAGE_CONNECTION_STRING)
        else:
            from azure.identity import DefaultAzureCredential
            _client = BlobServiceClient(config.STORAGE_ACCOUNT_URL, credential=DefaultAzureCredential())
    return _client

def container():
    c = client().get_container_client(config.BLOB_CONTAINER)
    if not c.exists():
        c.create_container()
    return c

def upload(name: str, data, content_type: str):
    from azure.storage.blob import ContentSettings
    container().upload_blob(name, data, overwrite=False,
                            content_settings=ContentSettings(content_type=content_type))

def download_url(name: str, minutes: int = 10) -> str:
    """Generate a short-lived read-only SAS: the browser downloads straight from storage, bypassing the API."""
    svc = client()
    start = datetime.now(timezone.utc) - timedelta(minutes=1)
    expiry = datetime.now(timezone.utc) + timedelta(minutes=minutes)
    kwargs = dict(account_name=svc.account_name, container_name=config.BLOB_CONTAINER,
                  blob_name=name, permission=BlobSasPermissions(read=True), expiry=expiry, start=start)
    if config.STORAGE_CONNECTION_STRING:
        kwargs["account_key"] = svc.credential.account_key          # local Azurite: account key SAS
    else:
        kwargs["user_delegation_key"] = svc.get_user_delegation_key(start, expiry)  # Azure: user delegation SAS
    sas = generate_blob_sas(**kwargs)
    if config.BLOB_PUBLIC_BASE:   # local: Azurite uses path-style URLs, forwarded via the gateway's /blob/
        return f"{config.BLOB_PUBLIC_BASE.rstrip('/')}/{svc.account_name}/{config.BLOB_CONTAINER}/{name}?{sas}"
    return f"{svc.url.rstrip('/')}/{config.BLOB_CONTAINER}/{name}?{sas}"
ORDERS_EOF
mkdir -p app/orders
cat > app/orders/worker.py <<'ORDERS_EOF'
"""Background worker: consumes and processes order messages. Processing is idempotent — a message delivered twice is processed only once."""
import time
from . import db, queueing
from .log import get_logger, info

log = get_logger("worker")

def handle(msg):
    order_id = msg["order_id"]
    with db.pool.connection() as conn:
        row = conn.execute("SELECT item FROM orders WHERE id=%s", (order_id,)).fetchone()
        if row and row["item"] == "poison":
            raise ValueError("simulated unprocessable poison message")
        time.sleep(0.5)                                   # simulate slow processing
        cur = conn.execute("""UPDATE orders SET status='processed', processed_at=now()
                              WHERE id=%s AND status='pending'""", (order_id,))
    info(log, "order processed", order_id=order_id, changed=cur.rowcount)

def main():
    db.ensure_open()
    info(log, "worker started")
    queueing.consume(handle)
    db.pool.close()
    info(log, "worker stopped gracefully")

if __name__ == "__main__":
    main()
ORDERS_EOF
mkdir -p app/tests
cat > app/tests/test_db.py <<'ORDERS_EOF'
"""Integration tests: Testcontainers starts a real PostgreSQL 17 (not a mock) and removes the container afterwards.
Run: pip install -r requirements-dev.txt && pytest -q"""
import os
import psycopg
import pytest
from testcontainers.community.postgres import PostgresContainer   # new 4.x path (old path deprecated)


@pytest.fixture(scope="session")
def db_url():
    with PostgresContainer("postgres:17", driver=None) as pg:      # driver=None → postgresql://… (usable directly by psycopg 3)
        os.environ["DATABASE_URL"] = pg.get_connection_url()
        yield os.environ["DATABASE_URL"]


def test_migrations_are_idempotent(db_url):
    from orders import config, migrate
    config.DATABASE_URL = db_url
    migrate.main()
    migrate.main()                                                  # second run must not re-apply anything
    with psycopg.connect(db_url) as conn:
        versions = [r[0] for r in conn.execute("SELECT version FROM schema_migrations ORDER BY 1")]
    assert versions == ["001_init.sql", "002_expand_customer_email.sql"]


def test_idempotency_key_prevents_duplicates(db_url):
    sql = """INSERT INTO orders (item, qty, idempotency_key) VALUES ('book', 1, 'k-1')
             ON CONFLICT (idempotency_key) DO NOTHING RETURNING id"""
    with psycopg.connect(db_url) as conn:
        first = conn.execute(sql).fetchone()
        second = conn.execute(sql).fetchone()
        count = conn.execute("SELECT count(*) FROM orders WHERE idempotency_key='k-1'").fetchone()[0]
    assert first is not None and second is None and count == 1


def test_qty_must_be_positive(db_url):
    with psycopg.connect(db_url) as conn, pytest.raises(psycopg.errors.CheckViolation):
        conn.execute("INSERT INTO orders (item, qty) VALUES ('bad', 0)")
ORDERS_EOF
mkdir -p azure
cat > azure/deploy.sh <<'ORDERS_EOF'
#!/usr/bin/env bash
# hour 6: deploy orders to Azure (Container Apps + PostgreSQL Flexible Server + Azure Managed Redis
#        + Service Bus + Blob Storage + Key Vault), all accessed via a user-assigned managed identity, with no long-lived keys in connection strings (Redis/PG passwords live in Key Vault).
# Usage: bash azure/deploy.sh    Clean up: az group delete -n $RG --yes --no-wait
set -euo pipefail
: "${LOC:=canadacentral}"; : "${RG:=rg-docker-hour6}"
SUFFIX=${SUFFIX:-$(openssl rand -hex 3)}
ACR=acrorders$SUFFIX; ENV=cae-orders; ID=id-orders; KV=kv-orders-$SUFFIX
PG=pg-orders-$SUFFIX; REDIS=redis-orders-$SUFFIX; SB=sb-orders-$SUFFIX; ST=storders$SUFFIX
DB_PASSWORD=$(openssl rand -base64 24 | tr -d '/+=')
echo "RG=$RG LOC=$LOC SUFFIX=$SUFFIX" | tee ~/hour6.env

az extension add -n containerapp --upgrade -y -o none
az extension add -n redisenterprise --upgrade -y -o none
az group create -n $RG -l $LOC -o none

# ---------- Identity ----------
az identity create -g $RG -n $ID -o none
ID_RID=$(az identity show -g $RG -n $ID --query id -o tsv)
ID_PID=$(az identity show -g $RG -n $ID --query principalId -o tsv)
ID_CID=$(az identity show -g $RG -n $ID --query clientId -o tsv)

# ---------- Images ----------
az acr create -g $RG -n $ACR --sku Basic -o none
az role assignment create --assignee-object-id $ID_PID --assignee-principal-type ServicePrincipal \
  --role AcrPull --scope $(az acr show -n $ACR --query id -o tsv) -o none
az acr build -r $ACR -t orders:1.0 ./app --no-logs
az acr build -r $ACR -t orders-web:1.0 ./web --no-logs

# ---------- Data: PostgreSQL Flexible Server ----------
az postgres flexible-server create -g $RG -n $PG -l $LOC --version 17 \
  --tier Burstable --sku-name Standard_B1ms --storage-size 32 \
  --admin-user orders --admin-password "$DB_PASSWORD" \
  --public-access 0.0.0.0 --yes -o none          # 0.0.0.0 = allow access from Azure services; in production use VNet integration/private endpoints
az postgres flexible-server db create -g $RG -s $PG -d orders -o none
PG_HOST=$(az postgres flexible-server show -g $RG -n $PG --query fullyQualifiedDomainName -o tsv)

# ---------- Cache: Azure Managed Redis ----------
az redisenterprise create -g $RG --cluster-name $REDIS -l $LOC --sku Balanced_B0 \
  --clustering-policy EnterpriseCluster --access-keys-auth Enabled -o none
REDIS_HOST=$(az redisenterprise show -g $RG --cluster-name $REDIS --query hostName -o tsv)
REDIS_KEY=$(az redisenterprise database list-keys -g $RG --cluster-name $REDIS --query primaryKey -o tsv)

# ---------- Queue: Service Bus ----------
az servicebus namespace create -g $RG -n $SB -l $LOC --sku Standard -o none
az servicebus queue create -g $RG --namespace-name $SB -n orders --max-delivery-count 5 -o none
SB_ID=$(az servicebus namespace show -g $RG -n $SB --query id -o tsv)
for r in "Azure Service Bus Data Sender" "Azure Service Bus Data Receiver"; do
  az role assignment create --assignee-object-id $ID_PID --assignee-principal-type ServicePrincipal --role "$r" --scope $SB_ID -o none
done

# ---------- Object storage: Blob ----------
az storage account create -g $RG -n $ST -l $LOC --sku Standard_LRS --kind StorageV2 \
  --allow-blob-public-access false --allow-shared-key-access false --min-tls-version TLS1_2 -o none
az role assignment create --assignee-object-id $ID_PID --assignee-principal-type ServicePrincipal \
  --role "Storage Blob Data Contributor" --scope $(az storage account show -g $RG -n $ST --query id -o tsv) -o none

# ---------- Secrets: Key Vault (RBAC mode) ----------
az keyvault create -g $RG -n $KV -l $LOC --enable-rbac-authorization true -o none
KV_ID=$(az keyvault show -n $KV --query id -o tsv)
az role assignment create --assignee $(az ad signed-in-user show --query id -o tsv) --role "Key Vault Secrets Officer" --scope $KV_ID -o none
az role assignment create --assignee-object-id $ID_PID --assignee-principal-type ServicePrincipal --role "Key Vault Secrets User" --scope $KV_ID -o none
sleep 30   # wait for RBAC to take effect
az keyvault secret set --vault-name $KV -n database-url -o none \
  --value "postgresql://orders:${DB_PASSWORD}@${PG_HOST}:5432/orders?sslmode=require"
az keyvault secret set --vault-name $KV -n redis-url -o none --value "rediss://:${REDIS_KEY}@${REDIS_HOST}:10000/0"
KV_URI=https://$KV.vault.azure.net/secrets

# ---------- Runtime: Container Apps ----------
# Connection budget (B1ms has only 35 user connections, and Burstable has no built-in PgBouncer):
#   api 5 replicas × 2 gunicorn processes × pool 2 = 20; worker 4 × 1 × 2 = 8; two jobs ≤ 2 each → total ≤ 32 < 35
az containerapp env create -g $RG -n $ENV -l $LOC -o none
IMG=$ACR.azurecr.io/orders:1.0
SECRETS="database-url=keyvaultref:$KV_URI/database-url,identityref:$ID_RID redis-url=keyvaultref:$KV_URI/redis-url,identityref:$ID_RID"
COMMON_ENV="DATABASE_URL=secretref:database-url REDIS_URL=secretref:redis-url AZURE_CLIENT_ID=$ID_CID \
 QUEUE_BACKEND=servicebus SERVICEBUS_NAMESPACE=$SB.servicebus.windows.net \
 STORAGE_ACCOUNT_URL=https://$ST.blob.core.windows.net APP_VERSION=1.0 DB_POOL_SIZE=2"

# 1) Migration job (manually triggered, run once before every release)
az containerapp job create -g $RG -n job-migrate --environment $ENV --trigger-type Manual \
  --replica-timeout 600 --replica-retry-limit 1 --parallelism 1 --replica-completion-count 1 \
  --image $IMG --registry-server $ACR.azurecr.io --registry-identity $ID_RID --mi-user-assigned $ID_RID \
  --secrets $SECRETS --env-vars $COMMON_ENV --command orders-migrate \
  --cpu 0.25 --memory 0.5Gi -o none
az containerapp job start -g $RG -n job-migrate -o none
echo "Waiting for the migration to finish…"; sleep 60
az containerapp job execution list -g $RG -n job-migrate --query "[0].properties.status" -o tsv

# 2) API (internal ingress: only web in the same environment can reach it)
az containerapp create -g $RG -n ca-orders-api --environment $ENV --image $IMG \
  --registry-server $ACR.azurecr.io --registry-identity $ID_RID --user-assigned $ID_RID \
  --ingress internal --target-port 8000 --min-replicas 1 --max-replicas 5 \
  --cpu 0.5 --memory 1Gi --secrets $SECRETS --env-vars $COMMON_ENV -o none

# 3) Worker (no ingress; KEDA scales on Service Bus queue length, down to 0)
az containerapp create -g $RG -n ca-orders-worker --environment $ENV --image $IMG \
  --registry-server $ACR.azurecr.io --registry-identity $ID_RID --user-assigned $ID_RID \
  --command orders-worker --min-replicas 0 --max-replicas 4 \
  --scale-rule-name sb-orders --scale-rule-type azure-servicebus \
  --scale-rule-metadata "queueName=orders" "namespace=$SB" "messageCount=5" \
  --scale-rule-identity $ID_RID \
  --cpu 0.25 --memory 0.5Gi --secrets $SECRETS --env-vars $COMMON_ENV -o none

# 4) Daily report (scheduled job, cron in UTC)
az containerapp job create -g $RG -n job-report --environment $ENV --trigger-type Schedule \
  --cron-expression "15 6 * * *" --replica-timeout 900 --replica-retry-limit 2 \
  --parallelism 1 --replica-completion-count 1 \
  --image $IMG --registry-server $ACR.azurecr.io --registry-identity $ID_RID --mi-user-assigned $ID_RID \
  --secrets $SECRETS --env-vars $COMMON_ENV --command orders-report \
  --cpu 0.25 --memory 0.5Gi -o none

# 5) Web (external ingress, ACA-managed HTTPS; /api reverse-proxied to the internal API)
az containerapp create -g $RG -n ca-orders-web --environment $ENV --image $ACR.azurecr.io/orders-web:1.0 \
  --registry-server $ACR.azurecr.io --registry-identity $ID_RID --user-assigned $ID_RID \
  --ingress external --target-port 8080 --min-replicas 1 --max-replicas 3 \
  --cpu 0.25 --memory 0.5Gi --env-vars API_UPSTREAM=http://ca-orders-api -o none

FQDN=$(az containerapp show -g $RG -n ca-orders-web --query properties.configuration.ingress.fqdn -o tsv)
cat >> ~/hour6.env <<EOV
ACR=$ACR ENV=$ENV KV=$KV PG=$PG REDIS=$REDIS SB=$SB ST=$ST FQDN=$FQDN
EOV
echo "Done: https://$FQDN"
ORDERS_EOF
mkdir -p chaos
cat > chaos/base.yaml <<'ORDERS_EOF'
# hour 7: layered on top of the hour 6 compose.yaml; enables the fault-injection endpoints (lab environments only!)
services:
  api:
    environment:
      CHAOS_ENABLED: "1"
ORDERS_EOF
mkdir -p chaos
cat > chaos/blindbox.sh <<'ORDERS_EOF'
#!/usr/bin/env bash
# Fault blind box: bash chaos/blindbox.sh start [1-8] | traffic | answer <number> | reveal | reset
set -uo pipefail
cd "$(dirname "$0")/.."
DC=(docker compose -f compose.yaml -f chaos/base.yaml)
STATE=chaos/.state
NAMES=("" "connection pool exhaustion" "gunicorn worker timeout" "gateway read timeout 504" "wrong DNS resolution" "source port (SNAT) exhaustion" "CPU throttling" "OOM (memory limit)" "temp directory full")
case "${1:-}" in
  start)
    n=${2:-$(( RANDOM % 8 + 1 ))}
    sed 's/proxy_read_timeout 30s;/proxy_read_timeout 2s;/' gateway/nginx.conf > chaos/.nginx-f3.conf
    "${DC[@]}" -f chaos/f$n.yaml up -d --quiet-pull >/dev/null 2>&1
    echo "$n" | base64 > $STATE; date +%s >> $STATE
    echo "Blind box ready (${2:+picked #$n}${2:-random}). Run bash chaos/traffic.sh to see the symptoms, then start investigating.";;
  traffic) bash chaos/traffic.sh;;
  answer)
    n=$(head -1 $STATE | base64 -d); t0=$(sed -n 2p $STATE); el=$(( $(date +%s) - t0 ))
    if [ "${2:-}" = "$n" ]; then echo "✓ Correct: #$n ${NAMES[$n]}, took $((el/60)) min $((el%60)) s"; else echo "✗ Wrong, look for more evidence (hint: check the status codes and the first error in the api log)"; fi;;
  reveal) n=$(head -1 $STATE | base64 -d); echo "Answer: #$n ${NAMES[$n]} (injection file chaos/f$n.yaml)"; cat chaos/f$n.yaml;;
  reset) "${DC[@]}" up -d --force-recreate api gateway >/dev/null 2>&1; rm -f $STATE; echo "Normal configuration restored";;
  list) for i in $(seq 8); do echo "#$i ${NAMES[$i]}"; done;;
  *) echo "Usage: $0 start [1-8] | traffic | answer <1-8> | reveal | reset | list";;
esac
ORDERS_EOF
mkdir -p chaos
cat > chaos/f1.yaml <<'ORDERS_EOF'
services:
  api:
    environment:
      DB_POOL_SIZE: "2"
      DB_POOL_TIMEOUT: "3"
      GUNICORN_CMD_ARGS: "--threads 8"
ORDERS_EOF
mkdir -p chaos
cat > chaos/f2.yaml <<'ORDERS_EOF'
services:
  api:
    environment:
      GUNICORN_CMD_ARGS: "--timeout 3"
ORDERS_EOF
mkdir -p chaos
cat > chaos/f3.yaml <<'ORDERS_EOF'
services:
  gateway:
    volumes:
      - ./chaos/.nginx-f3.conf:/etc/nginx/conf.d/default.conf:ro
ORDERS_EOF
mkdir -p chaos
cat > chaos/f4.yaml <<'ORDERS_EOF'
services:
  api:
    extra_hosts:
      - "postgres:10.255.255.1"
ORDERS_EOF
mkdir -p chaos
cat > chaos/f5.yaml <<'ORDERS_EOF'
services:
  api:
    sysctls:
      net.ipv4.ip_local_port_range: "60000 60007"
ORDERS_EOF
mkdir -p chaos
cat > chaos/f6.yaml <<'ORDERS_EOF'
services:
  api:
    deploy:
      resources:
        limits: { cpus: "0.1", memory: 256M }
ORDERS_EOF
mkdir -p chaos
cat > chaos/f7.yaml <<'ORDERS_EOF'
services:
  api:
    deploy:
      resources:
        limits: { cpus: "0.5", memory: 128M }
ORDERS_EOF
mkdir -p chaos
cat > chaos/f8.yaml <<'ORDERS_EOF'
services:
  api:
    tmpfs:
      - /tmp:size=64k
ORDERS_EOF
mkdir -p chaos
cat > chaos/traffic.sh <<'ORDERS_EOF'
#!/usr/bin/env bash
# Mixed traffic: normal requests + slow requests + computation + uploads. Prints status-code counts and the slowest requests.
B=${B:-https://localhost:8443}
head -c 600K /dev/urandom > /tmp/upload-600k.bin
run() { xargs -P "$1" -I{} bash -c 'sleep 0.3; 
  set -- {}; m=$1; p=$2
  case $m in
    GET)    o=$(curl -sk -o /dev/null -w "%{http_code} %{time_total}" --max-time 40 "$0$p");;
    POST)   o=$(curl -sk -o /dev/null -w "%{http_code} %{time_total}" --max-time 40 -X POST "$0$p" -H "Content-Type: application/json" -d "{\"item\":\"t\",\"qty\":1}");;
    UPLOAD) o=$(curl -sk -o /dev/null -w "%{http_code} %{time_total}" --max-time 40 -F file=@/tmp/upload-600k.bin "$0$p");;
  esac
  echo "$o $m $p"' "$B"; }
echo "Phase 1: 12 concurrent report queries (about 4 s each)…"
for i in $(seq 12); do echo "GET /api/chaos/dbsleep?s=4"; done | run 12 > /tmp/traffic.out
echo "Phase 2: 40 mixed requests…"
{
  for i in $(seq 10); do echo "GET /api/stats"; echo "POST /api/orders"; done
  for i in $(seq 6); do echo "GET /api/chaos/cpu?ms=40"; done
  for i in $(seq 5); do echo "GET /api/chaos/leak?mb=4"; done
  for i in $(seq 3); do echo "GET /api/chaos/sleep?s=4"; echo "UPLOAD /api/files"; done
} | shuf | run 4 >> /tmp/traffic.out
echo "== Status code counts =="; awk '{print $1}' /tmp/traffic.out | sort | uniq -c
echo "== Per endpoint (status count avg-time) =="; awk '{k=$1" "$3" "$4; n[k]++; t[k]+=$2} END {for (k in n) printf "%-50s %3d  %.2fs\n", k, n[k], t[k]/n[k]}' /tmp/traffic.out | sort -k2
ORDERS_EOF
mkdir -p gateway
cat > gateway/nginx.conf <<'ORDERS_EOF'
# Gateway: HTTPS termination, HTTP→HTTPS redirect, rate limiting, static SPA, reverse proxy for the API and Blob
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
log_format json escape=json '{"time":"$time_iso8601","remote":"$remote_addr","method":"$request_method",'
  '"uri":"$request_uri","status":$status,"bytes":$body_bytes_sent,"rt":$request_time,'
  '"upstream":"$upstream_addr","urt":"$upstream_response_time","rid":"$request_id"}';

server {
    listen 80;
    return 301 https://$host:8443$request_uri;
}

server {
    listen 443 ssl;
    http2 on;
    ssl_certificate     /etc/nginx/certs/tls.crt;
    ssl_certificate_key /etc/nginx/certs/tls.key;
    ssl_protocols       TLSv1.2 TLSv1.3;

    access_log /dev/stdout json;
    client_max_body_size 10m;
    add_header Strict-Transport-Security "max-age=31536000" always;
    add_header X-Content-Type-Options nosniff always;

    resolver 127.0.0.11 valid=10s ipv6=off;     # Docker embedded DNS: re-resolve every 10 s to discover scaled replicas
    set $api  http://api:8000;
    set $blob http://azurite:10000;

    location / {
        root /usr/share/nginx/html;
        try_files $uri /index.html;
    }
    location /api/ {
        limit_req zone=api burst=20 nodelay;
        limit_req_status 429;
        proxy_set_header Host $host;
        proxy_set_header X-Request-ID $request_id;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_connect_timeout 3s;
        proxy_read_timeout 30s;
        proxy_pass $api;
    }
    location /blob/ {                              # local demo only: on Azure the browser talks to the Blob endpoint directly
        rewrite ^/blob/(.*)$ /$1 break;
        proxy_set_header Host azurite:10000;       # the SAS signature does not depend on Host, but Azurite identifies the account by path
        proxy_pass $blob;
    }
}
ORDERS_EOF
mkdir -p perf
cat > perf/load.js <<'ORDERS_EOF'
// hour 7: k6 load-test script. Hits api directly inside the Compose network (bypassing the gateway rate limit to measure the app's own capacity):
//   docker run --rm -i --network orders_default -e BASE=http://api:8000 grafana/k6 run - < perf/load.js
import http from 'k6/http';
import { check, sleep } from 'k6';

const BASE = __ENV.BASE || 'http://api:8000';
export const options = {
  insecureSkipTLSVerify: true,              // self-signed certificate
  stages: [
    { duration: '20s', target: 10 },        // ramp up to 10 virtual users
    { duration: '40s', target: 10 },        // hold
    { duration: '10s', target: 0 },
  ],
  thresholds: {
    http_req_failed: ['rate<0.01'],          // error rate < 1%
    http_req_duration: ['p(95)<300', 'p(99)<800'],
  },
};

export default function () {
  const r1 = http.get(`${BASE}/api/stats`);
  check(r1, { 'stats 200': (r) => r.status === 200 });
  const r2 = http.get(`${BASE}/api/chaos/cpu?ms=20`);            // simulate 20 ms of business logic
  check(r2, { 'cpu 200': (r) => r.status === 200 });
  const r3 = http.post(`${BASE}/api/orders`, JSON.stringify({ item: 'k6', qty: 1 }),
    { headers: { 'Content-Type': 'application/json' } });
  check(r3, { 'order accepted': (r) => r.status === 202 });
  sleep(0.5);
}
ORDERS_EOF
mkdir -p web
cat > web/.dockerignore <<'ORDERS_EOF'
Dockerfile
ORDERS_EOF
mkdir -p web
cat > web/Dockerfile <<'ORDERS_EOF'
# Front end + reverse proxy on Azure (ACA terminates HTTPS, so this only listens on HTTP 8080)
FROM nginx:1.29-alpine
COPY nginx-aca.conf.template /etc/nginx/templates/default.conf.template
COPY index.html /usr/share/nginx/html/index.html
EXPOSE 8080
ORDERS_EOF
mkdir -p web
cat > web/index.html <<'ORDERS_EOF'
<!DOCTYPE html>
<html lang="zh-CN"><head><meta charset="utf-8"><title>Orders Demo</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>body{font-family:system-ui,sans-serif;max-width:760px;margin:2rem auto;padding:0 1rem}
fieldset{margin:1rem 0}table{border-collapse:collapse;width:100%}td,th{border:1px solid #ccc;padding:4px 8px}
.pending{color:#b45309}.processed{color:#047857}pre{background:#f4f4f5;padding:.5rem;overflow:auto}</style></head>
<body>
<h1>Orders Demo</h1>
<fieldset><legend>Place an order (with Idempotency-Key)</legend>
 <input id="item" value="book"> × <input id="qty" type="number" value="1" min="1" style="width:4em">
 <button onclick="order()">Place order</button> <button onclick="order(true)">Resubmit the same request</button></fieldset>
<fieldset><legend>Stats (cached in Redis for 10 s)</legend><button onclick="stats()">Refresh</button><pre id="stats"></pre></fieldset>
<fieldset><legend>Upload a file (Blob + short-lived SAS)</legend><input type="file" id="file"> <button onclick="upload()">Upload</button> <span id="link"></span></fieldset>
<h2>Recent orders</h2><table><thead><tr><th>ID</th><th>Item</th><th>Qty</th><th>Status</th></tr></thead><tbody id="rows"></tbody></table>
<script>
let lastKey = null;
async function order(repeat){
  const key = repeat && lastKey ? lastKey : crypto.randomUUID(); lastKey = key;
  const r = await fetch('/api/orders',{method:'POST',headers:{'Content-Type':'application/json','Idempotency-Key':key},
    body:JSON.stringify({item:item.value,qty:+qty.value})});
  alertBox(await r.json()); load();
}
function alertBox(o){ stats_.textContent = JSON.stringify(o,null,2) }
const stats_ = document.getElementById('stats');
async function stats(){ alertBox(await (await fetch('/api/stats')).json()) }
async function load(){
  const rows = await (await fetch('/api/orders')).json();
  document.getElementById('rows').innerHTML = rows.map(o=>`<tr><td>${o.id}</td><td>${o.item}</td><td>${o.qty}</td><td class="${o.status}">${o.status}</td></tr>`).join('');
}
async function upload(){
  const fd = new FormData(); fd.append('file', file.files[0]);
  const j = await (await fetch('/api/files',{method:'POST',body:fd})).json();
  link.innerHTML = `<a href="$%7Bj.url%7D" target="_blank">Download (valid for 10 minutes)</a>`;
}
load(); setInterval(load, 2000);
</script></body></html>
ORDERS_EOF
mkdir -p web
cat > web/nginx-aca.conf.template <<'ORDERS_EOF'
# At startup the official nginx image uses envsubst to replace ${API_UPSTREAM} with the environment variable (only defined variables are substituted)
server {
    listen 8080;
    client_max_body_size 10m;
    add_header X-Content-Type-Options nosniff always;

    location = /healthz { return 200 "ok\n"; }
    location / {
        root /usr/share/nginx/html;
        try_files $uri /index.html;
    }
    location /api/ {
        proxy_pass ${API_UPSTREAM};          # e.g. http://ca-orders-api (internal ingress in the same ACA environment)
        proxy_set_header X-Request-ID $request_id;
        proxy_set_header X-Forwarded-For $http_x_forwarded_for;
        proxy_read_timeout 30s;
    }
}
ORDERS_EOF
chmod +x gen-cert.sh azure/deploy.sh app/bin/*
echo "Generated $D: $(find . -type f | wc -l) files"
bash orders-bootstrap.sh                 # overwrite/add the files in ~/orders
cd ~/orders; [ -f .env ] || { cp .env.example .env; sed -i "s/change-me-db/$(openssl rand -hex 12)/; s/change-me-mq/$(openssl rand -hex 12)/" .env; }
[ -f gateway/certs/tls.crt ] || ./gen-cert.sh
alias dc='docker compose -f compose.yaml -f chaos/base.yaml'   # every command in this hour layers chaos/base.yaml on top
dc up -d --build
curl -sk https://localhost:8443/api/chaos/sleep?s=0.1
{"slept":0.1}

2. Install the diagnostic tools

sudo apt-get update && sudo apt-get install -y strace tcpdump jq pipx
sudo pipx install py-spy && sudo ln -sf /root/.local/bin/py-spy /usr/local/bin/py-spy   # or: sudo PIPX_BIN_DIR=/usr/local/bin pipx install py-spy
docker pull nicolaka/netshoot:v0.16    # the "Swiss Army knife" image for network troubleshooting (released 2026-07; for production debugging also pin it by digest)
docker pull grafana/k6:2.4.0           # load testing (Module 4)
py-spy --version; strace -V | head -1; tcpdump --version | head -1; nsenter --version
docker version --format 'engine={{.Server.Version}}'; docker buildx version
py-spy 0.4.3
strace -- version 6.8
tcpdump version 4.99.4
nsenter from util-linux 2.39.3
engine=29.10.0
github.com/docker/buildx v0.39.0 …

py-spy 0.4.3, strace 6.8, tcpdump 4.99.4 and nsenter 2.39.3 are the versions that actually ran in the environment used to produce this hour; the strace / tcpdump versions in the Ubuntu 24.04 repositories are the same. py-spy installed with pipx is whatever the latest release on PyPI is (0.4.3 as of 2026-11-17).

3. Fault-injection endpoints (lab environment only)

EndpointWhat it doesUsed for
/api/chaos/sleep?s=4Waits s seconds in the application layer (holds one worker process/thread)Timeout chains, 502/504
/api/chaos/dbsleep?s=3SELECT pg_sleep(s), holds one pool connectionConnection pool exhaustion, statement_timeout
/api/chaos/cpu?ms=40Pure computation for ms millisecondsCPU throttling, load testing
/api/chaos/leak?mb=4Retains mb MB of memory on each callOOM
SecurityCHAOS_ENABLED is off by default and must never be turned on in production; the Azure deployment from hour 6 does not set it. The fault-injection files chaos/f1.yaml … f8.yaml are just Compose override files, and bash chaos/blindbox.sh reset restores everything at any time.

4. Baseline: first confirm what "normal" looks like

bash chaos/blindbox.sh reset
bash chaos/traffic.sh | sed -n '/Status code counts/,$p' | head -6
docker compose ps --format 'table {{.Service}}	{{.Status}}'
== Status code counts ==
     36 200
      3 201
     10 202
== Per endpoint (status count avg-time) ==
…
SERVICE    STATUS
api        Up 2 minutes (healthy)
…

The first rule of troubleshooting is "know what normal looks like". Save this baseline (bash chaos/traffic.sh > ~/baseline.txt) and compare every later fault against it.

Warm-up: answer from memory (30 seconds)

Hour 1: what "is" a container on the host?

An ordinary Linux process placed into several namespaces (PID, NET, MNT…) and constrained by cgroups. That is why ps, nsenter, strace and py-spy on the host can act on it directly, which is the foundation of Module 2 in this hour.

Hour 2: what does exit code 137 mean?

The process was killed by SIGKILL (128+9). The most common cause is exceeding the memory limit and being killed by the OOM killer; docker inspect shows OOMKilled=true. That is blind box #7.

Hour 6: how is the connection budget of orders calculated?

Connections per replica = gunicorn processes × pool size per process; the sum over all replicas (api, worker, jobs) must stay below the number of user connections the database allows. Both the connection pool exhaustion in Module 3 and the tuning in Module 4 must stay within this budget.

Environment self-check list

Module 1 · Troubleshooting methodology and toolbox

00:00 – 05:00 · Collect evidence first, then find the layer, then act; every layer has its "cheapest first piece of evidence"
5 minMethodology + tool map★★★★★
Learning objectives
  • Narrow the scope through the six layers "application → process → container → network → host → cloud platform", and name the cheapest first piece of evidence for each layer.
  • Use USE (resources: utilization, saturation, errors) and RED (services: rate, errors, duration) to choose which metrics to look at, and be able to analyze a "connection pool" as a resource too.
  • Save evidence with one script before restarting (inspect, events, logs, resources, connections, stacks), and write "collect evidence first, then mitigate" into the runbook.
  • Know the prerequisites and limits of each way of "getting into a container from outside" (exec, nsenter, a debug container sharing namespaces, docker debug) - hands-on in Module 2.
Prerequisites: Hour 1 (container = a restricted Linux process), Hour 2 (exit codes, resource limits, health checks). Importance: ★★★★★ (the next seven modules all follow this process)

What: the layered troubleshooting model

LayerTypical problemsCheapest first piece of evidenceWhere in this hour
ApplicationExceptions, slow queries, deadlocks, connection pool exhaustion, external calls without a timeoutFirst exception in the application log, stacks (py-spy), RED metricsModules 2, 3
ProcessStuck in a system call, file descriptor exhaustion, zombie processes, signals not forwardedstrace, /proc/<pid>/ (fd, status, limits, wchan)Module 2
ContainerOOM (137), CPU throttling, read-only filesystem, full tmpfs, wrong config/environment variablesdocker inspect (State, HostConfig), docker events, cgroup filesModules 4, 8
NetworkDNS, timeouts, connection refused, port exhaustion, MTUss, getent, tcpdump inside the container's namespaceModules 3, 6
HostFull disk, kernel parameters, full conntrack table, host-level pressuredf, dmesg, sysctl, /proc/pressure/*Modules 4, 6
Cloud platformPrivate DNS, SNAT, NSG, platform timeouts, quotasPlatform logs (ContainerAppSystemLogs), platform metrics and network diagnostic toolsModule 3 (Azure comparison)

Why: collect evidence first, then mitigate

"Try a restart" often makes the symptom go away for a while, but it also destroys the most valuable evidence: the process's stacks, connection states, memory usage, the container's State (including OOMKilled) and logs that have not yet been rotated. The right order is: ① save evidence with one script in 1–2 minutes → ② mitigate (restart, roll back, scale out) → ③ analyze the evidence offline to find the root cause → ④ fix and prevent recurrence. Mitigating and collecting evidence do not conflict - once it is scripted, collecting evidence costs only a minute or two more than restarting directly.

How: two metric methods

MethodTargetWhat to look atExample in orders
USE (Brendan Gregg)Resources: CPU, memory, disk, connection pool, source portsUtilization, Saturation (queuing), ErrorsConnection pool: connections in use / requests waiting to borrow a connection / PoolTimeout; CPU: utilization / nr_throttled, PSI / —
RED (Tom Wilkie)Services: API, gateway, workerRate of requests, Error rate, Duration distribution/api/orders: requests per second, 5xx ratio, P95/P99; the status code counts from traffic.sh are a mini RED

Two "duration" clues are especially useful: ① the duration of failed requests exactly equals some timeout value (3.0 s, 5.0 s, 30 s) - that layer's timeout fired (Module 3); ② no errors but every request is slow - look at resource saturation first (CPU throttling, PSI, Module 4).

When: which way to "get into the container"

ApproachGood forLimits
docker execThe image has a shell and toolsSlim / distroless images have no shell; leaves processes and files behind in the container
nsenter -t PID -nEntering the container's network namespace with tools on the hostNeeds root on the host; enters only the namespaces you specify
docker run --network container:X nicolaka/netshootShares the target container's network namespace and uses netshoot's built-in dig, tcpdump, ss, curlNeeds to pull an image; shares only the namespaces you specify
docker run --pid container:X --cap-add SYS_PTRACE …Shares the PID namespace to debug processes (strace, py-spy)Needs ptrace permission
docker debug XAttaches a shell with a toolbox to any container / image (including slim images without a shell); you can install more toolsShips with Docker Desktop, free for all users since 4.49 (2025-10); not available on Linux servers with only Docker Engine installed, but from Desktop you can debug a remote engine with docker debug --host ssh://user@vm container
Common misconceptions① "CPU is only 30%, so it can't be a resource problem" - a container's bottleneck is often quota throttling, not average utilization. ② "dig works, so DNS is fine" - the application goes through the system resolver (including /etc/hosts), so use getent. ③ "You can't use strace / tcpdump in production" - you can, but limit the time and the filters; py-spy sampling has almost no overhead. ④ "No errors in the logs means it's a network problem" - timeout faults often leave logs only in the outer layer, while the inner layer is still "waiting normally".

Observing a container from outside: three paths

Container orders-api-1 (namespaces) NET namespaceeth0 · 172.18.0.7 PID namespacegunicorn = PID 1 MNT namespace (image filesystem)python:3.13-slim: no tcpdump / strace cgroup: cpu.max · memory.max · cpu.stat · *.pressure Host: nsenter -t PID -n ss -tanpHost tools inside the container's NET namespace netshoot: --network container:orders-api-1Built-in dig / tcpdump / curl, shares NET Host: sudo py-spy dump --pid HOSTPID -sPython stacks in the container, seen from the host
Figure 1-1 Observing a container from outside, without changing the image or opening a shell in the container

Flowchart: the standard steps for an incident

① SymptomRED: what fails, how slow ② Evidenceevidence.sh (1–2 min) ③ MitigateRestart / roll back / scale ④ Find layerSix layers + USE ⑤ Special toolsstrace · py-spy · tcpdump ⑥ Fix + reviewEvidence + prevention ② must come before ③; ④⑤ can be done offline after mitigation, using the saved evidence
Figure 1-2 "Collect evidence first, then mitigate": once scripted, evidence collection adds only a minute or two

Interactive simulator: evidence collection and layer finding in one incident

Choose a scenario and play it. The normal flow walks through all six steps; the failure scenarios show the five most common ways evidence collection goes wrong, and the terminal shows the matching commands and typical output (example).

Ready.
$ # Alert: /api/orders 5xx ratio 8%, P99 3.1 s

The first command for each layer

LayerCommandQuestion it answers
Service (RED)bash chaos/traffic.sh / docker compose logs gateway --since 5mWhich endpoints fail, status codes, durations
Containerdocker compose ps; docker inspect -f '{{.State.OOMKilled}} {{.State.ExitCode}} {{.RestartCount}}' CIs it restarting, OOM, exit code
Containerdocker events --since 10m --filter container=CTimeline of die / oom / health_status events
Applicationdocker compose logs api --since 5m | grep -m1 -E 'Error|Traceback'The first exception (not the last one)
Configurationdocker inspect C -f '{{json .HostConfig}}' | jq '{NanoCpus,Memory,ExtraHosts,Sysctls,Tmpfs}'Have limits and overrides changed compared with the baseline
Resourcesdocker stats --no-stream; docker exec C cat /sys/fs/cgroup/cpu.statUSE: utilization and saturation
Process / networkPID=$(docker inspect -f '{{.State.Pid}}' C); sudo nsenter -t $PID -n ss -sHost PID of the container's main process; connection summary
Hostdf -h /var/lib/docker; cat /proc/pressure/{cpu,memory,io}; sudo dmesg -T | tailDisk, host pressure, kernel messages (OOM killer)

Why the "first" exception: a fault usually triggers a chain of errors (connection failure → retry → timeout → health check failure); the last log line is the result, the first one is closest to the cause. grep -m1 takes only the first match.

Lab 1: Write a "one-command evidence before restart" script (about 4 minutes)

Create the script (put it at ~/orders/ops/evidence.sh; it can go straight into the runbook):
#!/usr/bin/env bash
# Usage: sudo bash ops/evidence.sh orders-api-1   → creates an evidence-<container>-<time>/ directory
set -uo pipefail
C=${1:?container name}; T=$(date -u +%Y%m%dT%H%M%SZ); D="evidence-$C-$T"; mkdir -p "$D"
docker inspect "$C"                      > "$D/inspect.json"
docker logs --timestamps --tail 1000 "$C" > "$D/logs.txt" 2>&1
docker events --since 30m --until "$(date +%s)" --filter container="$C" > "$D/events.txt"
docker stats --no-stream "$C"            > "$D/stats.txt"
docker top "$C" -eo pid,ppid,stat,rss,etime,args > "$D/top.txt"
PID=$(docker inspect -f '{{.State.Pid}}' "$C")
if [ "$PID" != 0 ]; then
  nsenter -t "$PID" -n ss -tanp          > "$D/ss.txt" 2>&1
  for f in cpu.max cpu.stat cpu.pressure memory.current memory.max memory.events; do
    echo "== $f"; cat "/proc/$PID/root/sys/fs/cgroup/$f" 2>/dev/null
  done                                   > "$D/cgroup.txt"
  command -v py-spy >/dev/null && timeout 20 py-spy dump --pid "$PID" -s > "$D/pyspy.txt" 2>&1
fi
tar czf "$D.tgz" "$D" && echo "Evidence saved: $D.tgz"

Notes: docker events --until "$(date +%s)" (end time = "now") makes the command print past events and return immediately; /proc/PID/root is the container's root filesystem, so reading the cgroup files as the container sees them from the host needs no docker exec; when the container has exited (PID is 0), process-level evidence is skipped. Production use: the evidence bundle is archived with the incident ticket and analyzed offline during the review.

Inject a fault, collect evidence first, then mitigate:
bash chaos/blindbox.sh start 1 >/dev/null      # pick #1: connection pool exhaustion
bash chaos/traffic.sh >/dev/null & sleep 3      # keep slow requests in flight
sudo bash ops/evidence.sh orders-api-1
wait; bash chaos/blindbox.sh reset              # mitigate (simulates restart/rollback)
tar tzf evidence-orders-api-1-*.tgz | head; grep -c getconn evidence-orders-api-1-*/pyspy.txt
Evidence saved: evidence-orders-api-1-20261117T140211Z.tgz
evidence-orders-api-1-20261117T140211Z/
evidence-orders-api-1-20261117T140211Z/inspect.json
evidence-orders-api-1-20261117T140211Z/logs.txt
evidence-orders-api-1-20261117T140211Z/events.txt
…
6

After the restart, pyspy.txt in the evidence bundle still shows 6 threads stuck in ConnectionPool.getconn - exactly the key evidence for case ① in Module 3. If you restart first and investigate later, all you have left is the description "occasional 500s".

Read the evidence with USE: from cgroup.txt and ss.txt, fill in the table (one row each for CPU, memory, connection pool, source ports: utilization / saturation / errors), then compare with the baseline saved in Module 0.
D=$(ls -d evidence-orders-api-1-*/ | tail -1)
grep -A3 'cpu.stat' "$D/cgroup.txt"; grep -A1 'memory.events' "$D/cgroup.txt"
grep -c ':5432' "$D/ss.txt"; jq -r '.[0].State | "\(.Status) oom=\(.OOMKilled) restarts=\(.RestartCount // 0)"' "$D/inspect.json"

Cleanup: rm -rf evidence-* (keep them in a real incident).

Case 1: three recurrences caused by "a restart fixes everything"

Problem: once a week a service had all of its requests time out, and the on-call engineer fixed it each time with a restart. Fix: the third time, someone ran py-spy dump before restarting and found every thread stuck on the same third-party HTTP call - that library set no timeout, and the remote side occasionally stopped responding. The fix was a single line, timeout=5, plus adding "collect a py-spy dump, docker inspect and the last 1000 log lines before restarting" to the runbook. Limitation: the evidence script itself needs timeouts (this hour's script wraps py-spy in timeout 20), otherwise collecting evidence prolongs the outage.

Case 2: the "CPU is only 30%" misjudgment

Problem: monitoring showed an average CPU of 30%, so the team ruled out resources and spent two days investigating the network. Fix: following USE, check CPU saturation, not just utilization: nr_throttled/nr_periods in cpu.stat reached 40% and PSI some avg10 was above 30 - classic quota throttling (Module 4). Limitation: averages hide bursts; collecting throttling and PSI metrics requires a monitoring system that supports cgroup v2 (see the Prometheus course).

Case 3: too many logs to find the first one

Problem: after the database was briefly unavailable, api printed hundreds of retry errors per second, and log rotation flushed out the earliest connection refused. Fix: export logs by time window (--since / --until), add request IDs to structured logs (hour 6), and set sensible max-size / max-file for the log driver in Compose. Limitation: local logs are only a fallback; long-term retention belongs in a centralized logging system.

Common errors and fixes

nsenter: cannot open /proc/PID/ns/net: Permission denied

Cause: no root privileges, or the PID is not the host's view of the PID. Fix: sudo nsenter, and get the PID with docker inspect -f '{{.State.Pid}}'.

OCI runtime exec failed: exec failed: unable to start container process: exec: "sh": executable file not found in $PATH

Cause: the image has no shell (distroless, scratch or a slim image). Fix: don't rebuild the image to troubleshoot: use host tools + nsenter, a netshoot container sharing the namespace, or docker debug on Docker Desktop (Module 2).

docker: 'debug' is not a docker command

Cause: docker debug ships with Docker Desktop and is missing on Linux servers that have only Engine installed. Fix: use nsenter / netshoot on servers; or, on a computer with Desktop, run docker debug --host ssh://user@vm container-name.

Error response from daemon: cannot join network namespace of a non running container

Cause: the target container is in a crash loop, so there is no namespace to join. Fix: first check docker logs --tail 50 and the State from docker inspect; if you need to look at the filesystem, you can docker debug a stopped container, or docker commit it and start a copy with --entrypoint sh (note that the copy does not have the original fault conditions).

docker events never returns

Cause: without --until it keeps streaming new events. Fix: for history, add --until "$(date +%s)" (the current timestamp), and wrap it in timeout in scripts.

Command-line exercises
1. Without entering the container, list all ESTABLISHED connections to port 5432 in orders-api-1.
PID=$(docker inspect -f '{{.State.Pid}}' orders-api-1)
sudo nsenter -t $PID -n ss -tan state established '( dport = :5432 )'
2. List the oom and die events of all containers in the past hour, and return immediately.
docker events --since 1h --until "$(date +%s)" --filter event=oom --filter event=die \
  --format '{{.Time}} {{.Actor.Attributes.name}} {{.Action}} exit={{.Actor.Attributes.exitCode}}'
Scenario analysis
A 3 a.m. alert: the order endpoint has 10% 5xx, and the on-call colleague is about to restart api. How would you plan the next 5 minutes?

① 1 minute: look at RED (which endpoints, status codes, whether the duration equals some timeout value); ② 1–2 minutes: run the evidence script (inspect, events, logs, cgroup, ss, py-spy); ③ mitigate: restart, or roll back to the previous version in the release record; ④ afterwards: use the evidence bundle and the six-layer model to locate the cause - a fixed 3 s duration is most likely pool wait, 137 is OOM, Cannot assign requested address is source port exhaustion; ⑤ fix + prevent recurrence (timeout hierarchy, connection reuse, alert thresholds).

Verified teaching videos

▶
Containers From Scratch • Liz Rice • GOTO 2018 — GOTO Conferences
English · "builds" a container live in a few dozen lines of Go: namespaces, chroot, cgroups - shows why nsenter works
▶
Cgroups, namespaces, and beyond: what are containers made from? — Docker (Jérôme Petazzoni)
English · classic talk on what containers are made of; some details are based on cgroup v1

Official documentation and further reading

Video storyboard (about 60 seconds)

Shot 1 · 0–20s
Visual: an alert goes off and the on-call engineer's hand reaches for the "Restart" button; the frame freezes and an "evidence bundle" icon pops up beside it.
Narration: A restart stops the bleeding, but it also wipes out the stacks, the connection states and the exit reason. Spend one minute collecting evidence first.
Shot 2 · 20–45s
Visual: a six-step staircase - application, process, container, network, host, cloud platform - and on each step the "cheapest evidence" lights up: first exception, strace, inspect, ss, PSI, platform logs.
Narration: Walk down layer by layer, take the cheapest evidence at each layer first, then decide whether to bring out the specialized tools.
Shot 3 · 45–60s
Visual: two cards, USE and RED, flip over: for resources look at utilization, saturation, errors; for services look at rate, errors, duration.
Narration: In the next module, we look straight from the host into the container's processes and system calls.
or score ≥ 70% on the "Quiz" tab

Module 2 · Process- and Syscall-Level Troubleshooting

05:00 – 13:00 · Get into containers with nsenter, netshoot and docker debug; use the three "scalpels" tcpdump, strace and py-spy to see the network, the system calls and the line of code
8 minCore module ⭐py-spy / strace output measured★★★★★
Learning objectives
  • Use nsenter to bring host tools into a container's network / mount namespaces; use --network container: and --pid container: to let netshoot share the target container's namespaces; know where docker debug applies.
  • Use tcpdump to tell whether packets went out and who disconnected first (SYN / FIN / RST); use strace to tell which system call a process is stuck in (poll waiting on the network, futex waiting on a lock, connect waiting on a handshake); use py-spy to find the exact line of Python code that is stuck.
  • Use them safely in production: time-box them, narrow the filters, cap the packet count, and prefer the lowest-overhead tool.
Prerequisites: Module 1; Linux hour 7, Module 7 (Chinese) (the host view of strace, perf and eBPF). Importance: ★★★★★

What: container processes are visible on the host

The gunicorn inside a container is just an ordinary process on the host, placed in its own PID, NET and MNT namespaces. docker inspect -f '{{.State.Pid}}' gives its PID on the host; host root can: ① via /proc/PID/ns/*, enter its namespaces (nsenter); ② attach to it via ptrace (strace, py-spy); ③ read its filesystem through /proc/PID/root. So troubleshooting does not require installing any tools in the image.

The three scalpels

ToolQuestion it answersUsage with containersOverhead and caveats
tcpdumpDid the packet actually go out / arrive? Did the handshake complete? Who disconnected first (FIN / RST)? Are there retransmissions?sudo nsenter -t $PID -n tcpdump -i eth0 -nn port 5432Medium; always restrict the filter and packet count (-c 200), and mind sensitive data in packets
straceWhich system call is the process stuck in? (poll/epoll_wait waiting on the network, futex on a lock, connect on a handshake, write returning ENOSPC)sudo strace -f -tt -T -p HOST_PID -e trace=network,pollHigh: every system call pauses the traced process; attach for only a few seconds
py-spyWhich line of Python is it stuck on? Which function is CPU time spent in?sudo py-spy dump --pid HOST_PID -s; top; record -o flame.svgLow: sampling, does not pause the process, safe for production; for Java use jstack / async-profiler, for Go use pprof

How: four ways into a container (from least to most intrusive)

  1. Host tools + nsenter: sudo nsenter -t $PID -n ss -tanp. -n enters only the network namespace, so you run the host's ss binary yet see the container's connections. -m enters the mount namespace (to see the container's /etc/resolv.conf).
  2. A debug container sharing namespaces: docker run --rm -it --network container:orders-api-1 nicolaka/netshoot:v0.16. netshoot has its own filesystem (dig, tcpdump, curl, iperf, termshark…), but the same NIC, IP, ports and DNS configuration as the target container. Adding --pid container:X --cap-add SYS_PTRACE also lets it see and trace the target's processes.
  3. docker debug (Docker Desktop): attaches a shell with a toolbox to a container or image without modifying the image; you can install extra tools (from Nix packages), and it works on stopped containers. For servers, connect from Desktop to a remote engine with --host ssh://….
  4. docker exec: the most direct, but depends on the shell and tools in the image, and leaves processes behind inside the container.

When: which scalpel to pick

SymptomUse firstThen use
Request hangs and never returnspy-spy dump (which line it's stuck on)strace (which fd it's waiting on), then ls -l /proc/PID/fd/9 to confirm which connection fd 9 is
High CPU, slow responsespy-spy top / record (hot functions)Throttling evidence from Module 4
Connection failures, intermittent timeoutsss (state counts), tcpdump (handshakes and RSTs)strace return value of connect (ECONNREFUSED / EADDRNOTAVAIL / ETIMEDOUT)
File writes failerrno in the application logstrace -e trace=write,openat for a returned ENOSPC / EROFS
Security note netshoot with --cap-add NET_ADMIN,NET_RAW or SYS_PTRACE is very powerful; add these only when needed and remove the container as soon as you're done (--rm). The official netshoot README recommends pinning the image by digest for production debugging. Packets captured by tcpdump may contain tokens and personal data, so treat saved pcaps as sensitive data.

The same "stuck request": what each scalpel sees

py-spy: code line dbsleep (orders/chaos.py:19)Connection.execute (psycopg)Cursor.execute (psycopg)Connection.wait (psycopg) → waiting for the databaseOverhead: low (sampling) strace: system calls poll([{fd=9, POLLIN}], 1, 100) = 0 (Timeout)poll([{fd=9, POLLIN}], 1, 100) = 0 (Timeout) → no CPU used, waiting on fd 9Overhead: high (pauses every call) tcpdump: packets api:48214 → pg:5432 [P.] Querypg:5432 → api:48214 [.] ack(no data for 5 s)pg:5432 → api:48214 [P.] Error → DB got it, errors after 5 sOverhead: medium (filter it)
Figure 2-1 Top to bottom: code line → system call → packet. Only when the three corroborate each other do you have a complete chain of evidence

Namespace sharing: who shares what with whom

orders-api-1NET: eth0 172.18.0.7PID: gunicorn (1) + workersMNT: python:3.13-slimNo shell tools netshoot (debug container)NET: shared ← --network container:PID: shared ← --pid container:MNT: its own (dig, tcpdump…)Caps: SYS_PTRACE / NET_RAW Same NIC, same 127.0.0.11Sees its processes; can strace / py-spy
Figure 2-2 A debug container shares only the namespaces you specify; its filesystem is always its own, so the tools never pollute the target image

Interactive simulator: from symptom to line of code

Choose "which scalpel + environment conditions". Success scenarios go through attach → sample → conclusion; failure scenarios stop at the most common error and give an alternative (output is an example).

Ready.
$ curl -sk "https://localhost:8443/api/chaos/dbsleep?s=8" & # create a stuck request

Getting into a container

CommandDescription
PID=$(docker inspect -f '{{.State.Pid}}' orders-api-1)Host PID of the container's main process
docker top orders-api-1 -eo pid,argsHost PIDs of all processes in the container (gunicorn workers)
sudo nsenter -t $PID -n ss -tanpTCP connections inside the container (using the host's ss)
sudo nsenter -t $PID -n -m cat /etc/resolv.confEnter both the network and mount namespaces
docker run --rm -it --network container:orders-api-1 nicolaka/netshoot:v0.16Debug container sharing the network
docker run --rm -it --pid container:orders-api-1 --cap-add SYS_PTRACE nicolaka/netshoot:v0.16Debug container sharing PIDs (can strace)
docker debug orders-api-1 / docker debug --host ssh://user@vm orders-api-1Docker Desktop: attach a debug shell (local / remote engine)

The three scalpels

CommandDescription
sudo nsenter -t $PID -n tcpdump -i eth0 -nn -c 50 'tcp port 5432 and (tcp[tcpflags] & (tcp-syn|tcp-fin|tcp-rst) != 0)'Capture only handshakes and disconnects (SYN / FIN / RST)
sudo nsenter -t $PID -n tcpdump -i eth0 -w /tmp/api.pcap -c 2000Save to a pcap for analysis in Wireshark / termshark
sudo strace -f -tt -T -p $P -e trace=network,poll,epoll_waitAttach to a process and its threads; -T shows the time spent in each call
sudo timeout 5 strace -c -f -p $P5-second system call summary (which calls are most frequent and slowest)
sudo ls -l /proc/$P/fd/9What fd 9 is (socket:[123456], then find the matching connection in ss)
sudo py-spy dump --pid $PID -sCurrent call stacks of all processes / threads (-s includes subprocesses)
sudo py-spy top --pid $PID -sLive view of "which function uses the most CPU"
sudo py-spy record -o flame.svg --pid $PID -s -d 3030-second flame graph

Key flags: strace's -f traces all threads (required with gunicorn --threads); py-spy's -s (--subprocesses) includes the worker processes forked by the gunicorn master, so running it once against PID 1 is enough.

Lab 2: see connections, call stacks, system calls and handshakes without changing the image (about 7 minutes)

nsenter: view the container's network with host tools
PID=$(docker inspect -f '{{.State.Pid}}' orders-api-1); echo $PID
sudo nsenter -t $PID -n ip -br addr
sudo nsenter -t $PID -n ss -tan state established '( dport = :5432 or dport = :6379 )'
docker exec orders-api-1 sh -c 'which tcpdump strace || echo "No debug tools in the image"'
23817
lo               UNKNOWN        127.0.0.1/8 ::1/128
eth0@if31        UP             172.18.0.7/16
Recv-Q Send-Q Local Address:Port   Peer Address:Port
0      0      172.18.0.7:48214     172.18.0.3:5432
0      0      172.18.0.7:48230     172.18.0.3:5432
0      0      172.18.0.7:39872     172.18.0.4:6379
No debug tools in the image
netshoot: the full toolset inside the container's network
docker run --rm --network container:orders-api-1 nicolaka/netshoot:v0.16 \
  sh -c 'cat /etc/resolv.conf; dig +short postgres; nc -zv -w2 redis 6379'
nameserver 127.0.0.11
options ndots:0
172.18.0.3
Connection to redis (172.18.0.4) 6379 port [tcp/redis] succeeded!

127.0.0.11 is Docker's embedded DNS (hour 6 Module 3). Service names inside the container are resolved by it, and external domains are forwarded by it to the host's upstream DNS.

py-spy: view a container's Python call stack from the host
curl -sk "https://localhost:8443/api/chaos/dbsleep?s=5" & sleep 1
for c in orders-api-1 orders-api-2; do sudo py-spy dump --pid $(docker inspect -f '{{.State.Pid}}' $c) -s; done 2>/dev/null | grep -B3 -A1 dbsleep; wait
    Connection.wait (psycopg/connection.py:453)
    Cursor.execute (psycopg/cursor.py:93)
    Connection.execute (psycopg/connection.py:267)
    dbsleep (orders/chaos.py:19)
    Flask.dispatch_request (flask/app.py:902)

The call stack shows at a glance that "the request is stuck waiting for the database to return". py-spy reads the container's Python through /proc/PID/root, so nothing needs to be installed in the image. We check both replicas because the gateway may send the request to either one.

strace: what is the process waiting for?
curl -sk -o /dev/null -w '%{http_code} %{time_total}s\n' "https://localhost:8443/api/chaos/dbsleep?s=8" &
sleep 1; P=$(docker top orders-api-1 -eo pid,args | awk '/gunicorn/ {print $1}' | tail -1)
sudo timeout 2 strace -f -tt -p $P -e trace=network,poll 2>&1 | head -4; wait   # no output? use the PID of another worker / replica
sudo ls -l /proc/$P/fd/9
strace: Process 586 attached with 5 threads
[pid   586] 01:15:08.626224 poll([{fd=9, events=POLLIN|POLLERR}], 1, 100) = 0 (Timeout)
[pid   586] 01:15:08.727370 poll([{fd=9, events=POLLIN|POLLERR}], 1, 100) = 0 (Timeout)
500 5.00s
lrwx------ 1 10001 10001 64 Nov 17 01:15 /proc/586/fd/9 -> socket:[412233]

The process polls fd 9 (the database connection) every 100 ms - it isn't computing, it's waiting on the network. 500 5.00s comes from the statement_timeout=5000 set in hour 6 (analyzed in detail in Module 3).

tcpdump: look only at handshakes and disconnects
sudo nsenter -t $PID -n timeout 10 tcpdump -i eth0 -nn -c 6 \
  'tcp port 5432 and (tcp[tcpflags] & (tcp-syn|tcp-fin|tcp-rst) != 0)' &
docker compose restart api >/dev/null; wait
172.18.0.7.48214 > 172.18.0.3.5432: Flags [F.], seq 812, ack 2290 …
172.18.0.3.5432 > 172.18.0.7.48214: Flags [F.], seq 2290, ack 813 …
…

When api restarts, the old process exits, the kernel closes its sockets and sends FIN (F.), and the old network namespace then disappears, so you only see the first few lines. Note: after the restart, $PID has changed. In real troubleshooting it's more common to see an R (RST) from the other side: rejected by a firewall, cut off by a middlebox's idle timeout, or connecting to a port nobody is listening on.

docker debug (optional, Docker Desktop)
docker debug --host ssh://azureuser@your-vm orders-api-1
# once inside:
install tcpdump
entrypoint --print

install installs tools from the Nix package repository; they live only in the debug session's toolbox and are never written into the image; entrypoint --print prints the image's entrypoint command. Cleanup: this lab creates no new resources.

Case 1: the "5-second slowdown" in a distroless image

Problem: after a service switched to a distroless image, some requests were occasionally 5 seconds slow, and the image had no shell at all. Fix: docker run --network container:svc nicolaka/netshoot tcpdump -nn port 53 showed that every slow request coincided with an AAAA query that got no response, which was retried after waiting out resolv.conf's default 5-second timeout - an upstream DNS forwarder was dropping AAAA queries. After the forwarder was fixed, the problem disappeared. Limitation: a debug container has to pull its image, so in offline environments push netshoot to an internal registry in advance.

Case 2: strace makes the incident worse

Problem: during peak hours, the on-call engineer ran strace -f against a 32-thread Java process and forgot to exit; throughput dropped 80%, health checks timed out and the instance was taken out of rotation. Fix: the runbook now requires strace to run with timeout 5 + an -e trace= filter, or only as a -c summary; sampling tools (py-spy, async-profiler, perf) are preferred. Limitation: sampling tools can't see "the arguments of a system call that is waiting", so the two complement each other.

Case 3: the same RST, two causes

Problem: calls from a service to an internal API occasionally failed with Connection reset by peer. Fix: capturing on both ends at once and comparing showed that the client received an RST the server never sent - an intermediate load balancer's idle timeout (e.g. 350 seconds) was cutting long-lived connections. Setting the client connection pool's idle reclaim time below the middlebox's idle timeout made the problem go away. Limitation: when capturing on only one end, it's easy to mistake a middlebox's behavior for the peer's.

Common errors and fixes

Permission Denied: Try running again with elevated permissions by going 'sudo env "PATH=$PATH" !!' (py-spy)

Cause: ptrace permission is required. Fix: use sudo on the host; in a debug container add --cap-add SYS_PTRACE (and share --pid container:X). Ubuntu's Yama kernel.yama.ptrace_scope also blocks tracing by non-root users.

strace: attach: ptrace(PTRACE_SEIZE, 586): Operation not permitted

Cause: same as above, or the target process is already attached by another debugger (only one tracer at a time). Fix: sudo; make sure no strace / py-spy process is left over (grep TracerPid /proc/586/status).

tcpdump on the host's eth0 doesn't capture traffic between containers

Cause: traffic between containers goes over the Docker bridge (br-xxxx) and never passes through the host's physical NIC. Fix: capture from the container's point of view with nsenter -t $PID -n tcpdump -i eth0, or capture on the corresponding br-… / veth… interface on the host (find the bridge name with docker network inspect).

tcpdump: eth0: You don't have permission to perform this capture on that device (inside netshoot)

Cause: the debug container lacks packet-capture capabilities. Fix: --cap-add NET_ADMIN --cap-add NET_RAW, or use host tcpdump + nsenter instead.

py-spy reports Failed to find python version from target process

Cause: attached to a process that isn't Python (e.g. a tini / shell in front of gunicorn), or the process is still starting. Fix: find the real Python process with docker top C -eo pid,args, or add -s on the main process to include its children.

strace output shows only futex(…, FUTEX_WAIT_PRIVATE, …)

Cause: attached to a thread that is only waiting on a lock / condition variable (e.g. a Python thread waiting for the GIL or for the connection pool's Condition). Fix: use py-spy dump to see what the Python layer is waiting for; always add -f for multithreaded programs.

Command-line exercises
1. Find which TCP connection fd 9 in orders-api-1 corresponds to.
P=$(docker top orders-api-1 -eo pid,args | awk '/gunicorn/ {print $1}' | tail -1)
INODE=$(sudo readlink /proc/$P/fd/9 | tr -dc 0-9)
sudo nsenter -t $P -n ss -tanpe | grep "ino:$INODE"
2. Without installing any tools, use one command to get the call stacks of all Python threads in orders-api-1 and save them to a file.
sudo py-spy dump --pid $(docker inspect -f '{{.State.Pid}}' orders-api-1) -s > stacks-$(date +%s).txt
Scenario analysis
py-spy shows all threads stopped in ssl.SSLSocket.recv, strace shows poll repeatedly timing out on one fd, and tcpdump shows the peer never replies. Where might the root cause be? What do you do next?

All three scalpels point to "waiting for the peer (an external HTTPS service) to respond". The root cause lies downstream or in the network in between, while the application's problem is that it sets no read timeout, so threads wait forever and eventually exhaust the workers. Next: ① confirm the peer's reachability at the network layer (curl from another machine, compare DNS); ② add connect and read timeouts in the application (shorter than the gunicorn timeout, see Module 3); ③ add circuit breaking / retry with backoff so one slow dependency can't take down the whole service.

Verified teaching videos

▶
Linux Performance Tools, Brendan Gregg, part 1 of 2 — Brendan Gregg
English · A panorama of observability tools (including the overhead and usage of strace and tcpdump); host perspective, but the principles apply equally to containers

Official documentation

Video storyboard (about 70 seconds)

Shot 1 · 0–20s
Visual: an hourglass for a "stuck" request; the camera passes through the container shell and sees an ordinary process on the host, PID 23817.
Narration: A container's processes are fully visible on the host, so troubleshooting doesn't require installing tools in the image.
Shot 2 · 20–50s
Visual: three scalpels cut open the same request one after another: py-spy shows the line of code, strace shows poll on fd 9, tcpdump shows the database replying with an error after 5 seconds.
Narration: Code line, system call, packet - only when the three corroborate each other do you have a complete chain of evidence.
Shot 3 · 50–70s
Visual: an overhead gauge: py-spy green, tcpdump yellow, strace red, with "timeout 5" appearing next to the red.
Narration: In production, prefer low-overhead tools, and always time-box the high-overhead ones.
or score ≥ 70% on the "Quiz" tab

Module 3 · Connections and the Timeout Chain: Four Production Puzzles

13:00 – 21:00 · Connection pool exhaustion, 502/504 and timeout layering, private DNS, SNAT / source port exhaustion - each one injected, investigated and fixed on orders
8 minCore module ⭐Several outputs measured★★★★★
Learning objectives
  • Recognize and fix ① connection pool exhaustion, ② 502/504 and the timeout chain, ③ private network DNS and ④ SNAT / source port exhaustion; tell which layer is at fault from "status code + duration + where the log line is".
  • Design a correct timeout hierarchy: the further in a layer is, the shorter its timeout (statement < pool wait < gunicorn < nginx < platform), and explain why two equal layers make the returned status code random.
  • When troubleshooting DNS, use the same resolution path as the application (getent hosts, not just dig); know that Azure private endpoints depend on "the private DNS zone being linked to the VNet".
  • Identify source port exhaustion from the TIME_WAIT count in ss and EADDRNOTAVAIL; the fix is to reuse connections, not to widen the port range.
Prerequisites: the three tools from Module 2; Hour 6, Module 2 (connection pools and the connection budget) and Module 3 (the gateway and embedded DNS). Importance: ★★★★★

Case ① Connection pool exhaustion

Mechanism: each worker process has a connection pool with an upper limit (the pool size). When more requests use the database concurrently than the pool size, the extra requests queue to "borrow a connection"; if the wait exceeds DB_POOL_TIMEOUT, PoolTimeout is raised → 500. Sync workers (each process handles one request at a time) almost never exhaust the pool; as soon as you switch to threads (--threads 8) while the pool stays at 2, it happens.

Evidence: the 500s almost all take exactly the pool timeout (measured 3.01 s); the log shows psycopg_pool.PoolTimeout; py-spy shows many threads stuck in ConnectionPool.getconn; the connection count on the database side is not high. Fix: pool size ≥ per-process concurrency (thread count), while staying within the connection budget from hour 6; add statement_timeout for slow queries; send reporting queries to a read replica or an async task.

Case ② 502/504 and the timeout chain

A request passes through several layers, and each layer has its own timeout. Rule: the further in a layer is, the shorter its timeout. Otherwise the outer layer gives up first while the inner layer is still working - wasted resources and confusing status codes.

LayerSetting in this projectWhat the client sees on timeout
Azure Container Apps ingressHTTP request timeout 240 seconds (fixed by the platform)504 / connection closed
nginx gatewayproxy_read_timeout 30s, proxy_connect_timeout 3s504 Gateway Time-out (measured: with 3 s set, returns at 3.0 s)
gunicorn--timeout default 30 seconds → the worker is aborted and restartedgunicorn 23 measured returning 500, log [CRITICAL] WORKER TIMEOUT; if the connection is dropped outright, nginx reports 502
Borrowing from the connection poolDB_POOL_TIMEOUT (default 30 s)500 + PoolTimeout
PostgreSQL statementstatement_timeout=5000 (hour 6)500 + canceling statement due to statement timeout (measured 5.0 s)

Recommended hierarchy: statement 5 s < pool wait 3–5 s < gunicorn 25 s < nginx 30 s < platform 240 s; client retries need backoff and a cap. gunicorn and nginx both defaulting to 30 s is a common trap: both expire at the same moment, and the symptom flips randomly between 500 / 502 / 504.

Case ③ Private network DNS

Mechanism: on Azure, once a private endpoint is enabled for the database, pg-xxx.postgres.database.azure.com points via CNAME to privatelink.postgres.database.azure.com. It resolves to the private IP only when the private DNS zone is linked to your virtual network; otherwise it resolves to the public IP, and public access is disabled → connection timeout / refused. The resolution chain inside a container: application → Docker embedded DNS 127.0.0.11 → host resolver (systemd-resolved on Ubuntu) → Azure DNS 168.63.129.16.

Evidence: resolution inside the container differs from another machine in the VNet; the result is a public IP; connect() hangs (visible in strace). Locally we use extra_hosts to point postgres at an unroutable address to simulate "resolved to the wrong IP". Fix: link the private DNS zone; do not work around it with extra_hosts / hard-coded IPs; custom DNS servers must forward Azure private zones to 168.63.129.16.

Case ④ SNAT / source port exhaustion

Mechanism: every outbound TCP connection occupies one (source IP, source port) pair. The side that actively closes the connection enters TIME_WAIT (about 60 seconds on Linux), during which the port cannot be reused for the same destination. When connections are frequently opened and closed (no connection pool / keep-alive), the available source ports run out: locally you get EADDRNOTAVAIL: Cannot assign requested address; in the cloud, behind NAT, it is the SNAT ports the NAT device allocates to you that run out, which shows up as intermittent connection timeouts.

A real hazard in this project: Hour 6's queueing.publish() opens and closes a new RabbitMQ connection for every message. Evidence: ss -tan state time-wait | wc -l is large; errno 99 in the log. Fix: reuse long-lived connections / a connection pool, HTTP keep-alive (the capstone lab gives a reference implementation); on Azure configure a NAT Gateway for outbound traffic (64,512 SNAT ports per public IP), and reach Azure PaaS through private endpoints (no SNAT).

Common misconceptions① "Just raise the pool to 100" - that breaks the database connection limit (hour 6's connection budget) and pushes the problem onto the database. ② "Set every timeout to 300 seconds" - slow requests hold workers longer, throughput drops and the failure spreads. ③ "Widen ip_local_port_range to fix port exhaustion" - that only delays it; the root cause is short-lived connections. ④ "If dig works, DNS is ruled out" - see Lab ③ below.

The timeout chain: inner layers must time out first

Client / platform ingress (ACA 240 s) nginx proxy_read_timeout 30 s → 504 gunicorn --timeout 25 s (recommended) → WORKER TIMEOUT → 500/502 Pool wait DB_POOL_TIMEOUT 3–5 s → PoolTimeout → 500 PostgreSQL statement_timeout 5 s → query canceled → 500
Figure 3-1 The timeout chain: inner layers (bottom) must time out before outer layers (top) so the error message is as close to the root cause as possible

DNS resolution chain inside a container, and private endpoints

api container/etc/hosts first 127.0.0.11Docker embedded DNS Host resolversystemd-resolved 168.63.129.16Azure DNS Private DNS zonelinked → 10.0.2.4 Not linked→ public IP (disabled)
Figure 3-2 The application goes through getaddrinfo: /etc/hosts first, then embedded DNS; dig skips /etc/hosts and asks DNS directly

Source port exhaustion: short-lived vs long-lived connections

New connection per message (hour 6 publish)connect → publish → close → TIME_WAIT 60 s8 ports → 9th message EADDRNOTAVAILCloud: NAT SNAT ports used up → intermittent timeouts One reused long-lived connection per threadconnect once → publish N messages → heartbeatsTIME_WAIT stops growingReconnect once on drop (capstone lab)
Figure 3-3 The fix is to open fewer new connections, not to hand out more ports

Interactive simulator ①: one request through five layers

Pick a fault to inject and play: see which layer the request stops at, what status code the client gets, how long it takes and which log holds the evidence (output is illustrative; key numbers come from measurements in this lesson).

Ready.
$ curl -sk -w '%{http_code} %{time_total}s' "https://localhost:8443/api/chaos/dbsleep?s=4"

Interactive simulator ②: timeout hierarchy sliders

Adjust each layer's timeout and the request's actual duration to see which fires first and what the client receives; the "Default" button reproduces the trap of gunicorn and nginx both at 30 s.

CommandDescription
curl -sk -o /dev/null -w '%{http_code} %{time_total}s\n' URLStatus code + total duration: the first step in working out which layer timed out
docker compose logs api gateway --since 2m | grep -m3 -E 'PoolTimeout|WORKER TIMEOUT|upstream timed out'Which layer the timeout happened in (where the log line is)
docker exec orders-api-1 env | grep -E 'DB_POOL|GUNICORN'The actual pool and gunicorn configuration
getent hosts postgres / dig +short postgresThe application's resolution path (including /etc/hosts) / DNS only
dig @168.63.129.16 NAMECompare with Azure DNS's answer
sudo nsenter -t $PID -n ss -tan state time-wait | wc -lNumber of TIME_WAIT connections
sudo nsenter -t $PID -n ss -sSummary by state (estab, timewait, orphaned)
docker exec C cat /proc/sys/net/ipv4/ip_local_port_rangeAvailable source port range (per network namespace)
docker inspect C -f '{{.HostConfig.ExtraHosts}} {{.HostConfig.Sysctls}}'Whether any extra_hosts / sysctl overrides are set

Each case is injected with chaos/fN.yaml, traffic is generated by chaos/traffic.sh, and bash chaos/blindbox.sh reset restores everything at the end. Parts marked "measured" were verified in a process-level environment (same gunicorn 23 / psycopg 3.2 / nginx configuration).

Case ①: connection pool exhaustion
dc -f chaos/f1.yaml up -d api          # pool 2, --threads 8, 3 s borrow timeout
bash chaos/traffic.sh | head -12
docker compose logs api --no-log-prefix --since 2m | grep -m1 -o 'PoolTimeout.*'
docker exec orders-api-1 env | grep -E 'DB_POOL|GUNICORN'
Phase 1: 12 concurrent report queries (about 4 s each)…
== Status code counts ==
     28 200
      3 201
     10 202
      8 500
500 GET /api/chaos/dbsleep?s=4                       8  3.01s      ← duration = pool timeout
PoolTimeout: couldn't get a connection after 3.00 sec
DB_POOL_SIZE=2
DB_POOL_TIMEOUT=3
GUNICORN_CMD_ARGS=--threads 8

An interesting contrast: with the same configuration, ordinary requests actually get faster (threads raise concurrency). When the thread count > pool size, you must make "pool ≥ thread count" or limit how many requests use the database at once.

Case ②a: gunicorn timeout
bash chaos/blindbox.sh reset; dc -f chaos/f2.yaml up -d api     # --timeout 3
curl -sk -o /dev/null -w '%{http_code} %{time_total}s\n' "https://localhost:8443/api/chaos/sleep?s=8"
docker compose logs api --since 1m | grep -m2 -oE 'WORKER TIMEOUT \(pid:[0-9]+\)|was sent SIGKILL'
500 5.94s
WORKER TIMEOUT (pid:560)
was sent SIGKILL
Case ②b: gateway 504
bash chaos/blindbox.sh start 3 >/dev/null       # generates a gateway config with proxy_read_timeout 2s
curl -sk -o /dev/null -w '%{http_code} %{time_total}s\n' "https://localhost:8443/api/chaos/sleep?s=4"
docker compose logs gateway --since 1m | grep -m1 -o 'upstream timed out.*while reading response header'
504 2.0s
upstream timed out (110: Connection timed out) while reading response header from upstream

The same slow request: gunicorn expires first → 500; the gateway expires first → 504. The status code plus the duration tells you which layer timed out.

statement_timeout (innermost layer)
bash chaos/blindbox.sh reset
curl -sk -o /dev/null -w '%{http_code} %{time_total}s\n' "https://localhost:8443/api/chaos/dbsleep?s=8"
docker compose logs api --since 1m | grep -m1 -o 'canceling statement due to statement timeout'
500 5.00s
canceling statement due to statement timeout

The innermost layer expires first and the error message states the cause directly - that is the value of "inner layers time out first". The poll wait you saw with strace in Module 2 happens during these 5 seconds.

Case ③: DNS resolves to the wrong address
dc -f chaos/f4.yaml up -d api                       # extra_hosts: postgres → 10.255.255.1
docker compose ps api; docker compose logs api --since 1m | grep -m1 -oE 'pool initialization incomplete.*|timeout expired'
docker run --rm --network container:orders-api-1 nicolaka/netshoot:v0.16 sh -c 'getent hosts postgres; dig +short postgres'
docker exec orders-api-1 cat /etc/hosts | grep postgres
bash chaos/blindbox.sh reset
orders-api-1  … Restarting (3) …
pool initialization incomplete after 10 sec
10.255.255.1    postgres          ← getent follows /etc/hosts: the address the application actually uses
172.18.0.3                        ← dig asks DNS directly; the result looks "normal"
10.255.255.1	postgres

Key lesson: dig only queries DNS, while getent hosts follows the system resolution order (/etc/hosts first) - when troubleshooting, use the same resolution path as the application. A debug container joined with --network container: inherits the target container's /etc/hosts and /etc/resolv.conf, so getent inside netshoot reproduces what the application sees. If api is in a restart loop, joining its namespace may fail; in that case look directly at docker inspect -f '{{.HostConfig.ExtraHosts}}' orders-api-1. Azure private endpoints work the same way: if resolving from the application's environment gives a public IP, the private DNS zone is not linked to the VNet.

Case ④: source port exhaustion
dc -f chaos/f5.yaml up -d api                       # ip_local_port_range has only 8 ports
docker exec orders-api-1 cat /proc/sys/net/ipv4/ip_local_port_range
for i in $(seq 30); do curl -sk -o /dev/null -w '%{http_code} ' -X POST https://localhost:8443/api/orders -H 'Content-Type: application/json' -d '{"item":"snat","qty":1}'; done; echo
PID=$(docker inspect -f '{{.State.Pid}}' orders-api-1); sudo nsenter -t $PID -n ss -tan state time-wait | wc -l
docker compose logs api --since 1m | grep -m1 -o 'Cannot assign requested address'
bash chaos/blindbox.sh reset
60000	60007
202 202 202 202 202 202 202 202 500 500 202 500 …
9
Cannot assign requested address

Measured (separate network namespace, 50 ports, client closes actively): the 51st connection fails with OSError 99 EADDRNOTAVAIL, and there are exactly 50 TIME_WAIT entries. The output of ss … state time-wait includes a header line, so the count is one more than the number of connections. The fix: make publish() reuse a long-lived connection (capstone lab), not widen the port range.

Case 1: "Random timeouts that only happen at peak"

Problem: a payment service saw 1–2% of outbound requests time out at the daily peak, succeeding on retry. The application and network teams blamed each other for two weeks. Approach: ss -tan state time-wait | wc -l showed as many as 20,000 TIME_WAIT entries, because the HTTP client calling the payment gateway opened a new connection for every request; the SNAT ports in the cloud were exhausted, and new connections timed out at the NAT while waiting for a port. After sharing a single client with keep-alive (a connection pool), the timeout rate fell to 0, and a NAT Gateway was added for headroom. Limitation: long-lived connections must respect the idle timeouts of the peer and of middleboxes, with sensible idle reclamation.

Case 2: a slow endpoint with "random" status codes

Problem: an export endpoint occasionally took more than 30 seconds, and users sometimes saw 500, sometimes 502, sometimes 504. Approach: found that gunicorn and nginx were both at 30 seconds; changed gunicorn to 25 seconds and turned the export into an async task (hour 6, Module 4) returning 202 + a polling URL. Limitation: going async requires task-state storage and cleanup.

What the same problems look like on Azure

CaseEvidence on AzureFix
Connection pool exhaustionPoolTimeout in ContainerAppConsoleLogs_CL; PostgreSQL active_connections metric is not highPool ≥ concurrency; Burstable tier has no built-in PgBouncer (hour 6)
Timeout chainIngress fixed at 240 s; WORKER TIMEOUT in the logs; 5xx in the Requests metricgunicorn < platform timeout; move long jobs to async
Private DNSConnection timeouts in the app log; a debug session in the same environment resolves to a public IPLink the private DNS zone privatelink.postgres.database.azure.com to the VNet
SNAT exhaustionIntermittent outbound timeouts, concentrated on the same destination IP:portConnection reuse; NAT Gateway for outbound (64,512 SNAT ports per public IP); private endpoints for Azure services
ContainerAppConsoleLogs_CL
| where ContainerAppName_s == "ca-orders-api" and TimeGenerated > ago(1h)
| where Log_s has_any ("PoolTimeout", "WORKER TIMEOUT", "Cannot assign requested address", "timeout expired")
| summarize count() by bin(TimeGenerated, 5m), tostring(extract(@"(PoolTimeout|WORKER TIMEOUT|Cannot assign requested address|timeout expired)", 1, Log_s))
az containerapp exec -g $RG -n ca-orders-api --command "python -c \"import socket;print(socket.gethostbyname('$PG.postgres.database.azure.com'))\""

Common errors and fixes

psycopg_pool.PoolTimeout: couldn't get a connection after 3.00 sec

Cause: more requests use the database concurrently than the pool size (threads > pool), or slow queries hold connections for a long time. Fix: pool ≥ thread count, and check the connection budget; add statement_timeout to slow queries or move them off the request path. Many getconn / Condition.wait frames in py-spy point to this.

[CRITICAL] WORKER TIMEOUT (pid:560) / was sent SIGKILL

Cause: request handling exceeded gunicorn's --timeout. Fix: find where it is slow (py-spy); give external calls shorter timeouts; make long jobs async; keep the gunicorn timeout below the gateway's.

upstream timed out (110: Connection timed out) while reading response header from upstream

Cause: nginx proxy_read_timeout expired before the upstream did (504). Fix: check whether the hierarchy is inverted; do not just raise the gateway timeout.

The same slow request sometimes returns 500, sometimes 502, sometimes 504

Cause: gunicorn and nginx have the same timeout (both 30 s), so which one expires first is random. Fix: set gunicorn to 25 s to create a clear hierarchy.

dig works but the application connects to the wrong address / pool initialization incomplete after 10 sec

Cause: /etc/hosts (extra_hosts), search/ndots, the application's own DNS cache, or an unlinked private DNS zone. Fix: inside the application container, use getent hosts or Python socket.gethostbyname to reproduce the application's resolution path.

OSError: [Errno 99] Cannot assign requested address

Cause: source port exhaustion (short-lived connections + TIME_WAIT). Fix: reuse connections; in the cloud, add a NAT Gateway / private endpoints. Do not rely on kernel parameters such as tcp_tw_reuse to mask the problem.

Command-line exercises
1. Count how many times each kind of upstream error appears in the gateway log over the last 5 minutes.
docker compose logs gateway --since 5m --no-log-prefix \
  | grep -oE 'upstream timed out|Connection refused|no live upstreams|upstream prematurely closed' | sort | uniq -c
2. Reproduce, inside orders-api-1, the postgres address the application sees (without netshoot).
docker exec orders-api-1 python -c "import socket; print(socket.gethostbyname('postgres'))"
Scenario analysis
After switching to --threads 4, throughput went up, but every day during the 9 a.m. reporting peak 2% of requests return 500, all taking about 30 seconds. How do you pin it down, and what fixes do you propose at two levels?

Duration ≈ 30 s and only during the reporting peak: most likely the pool wait (DB_POOL_TIMEOUT defaults to 30 s), with slow report queries holding every connection. Evidence: PoolTimeout in the log, getconn in py-spy. Fixes: ① configuration level - pool ≥ thread count (and check the connection budget), and lower the pool wait to 3–5 s so the error surfaces sooner; ② architecture level - add statement_timeout to report queries and send them to a read replica or an async task, so they do not compete with order placement for the same pool.

Verified teaching videos

▶
Container Networking From Scratch - Kristen Jacobs, Oracle — CNCF
English · builds container networking by hand from veth and bridges to NAT - see where source address translation and ports come from

Official documentation

Video storyboard (about 75 seconds)

Shot 1 · 0–25s
Visual: five concentric rings (platform, gateway, gunicorn, connection pool, database), each with a countdown; a slow request passes through from the outside in.
Narration: Every layer has a timeout, and the inner one must fire first.
Shot 2 · 25–50s
Visual: two countdowns hit zero at the same moment, and 500, 502 and 504 flash randomly on screen.
Narration: When two layers have the same timeout, the status code becomes a roll of the dice.
Shot 3 · 50–75s
Visual: on the left, a string of short-lived connections leaves a dense trail of TIME_WAIT footprints; on the right, one long-lived connection sends messages steadily.
Narration: The cure for port exhaustion is not more ports, but fewer new connections.
or score ≥ 70% on the "Quiz" tab

Module 4 · Performance and Cost Optimization

21:00 – 29:00 · Tune with data, not gut feeling: throttling, pressure stalls, latency distribution and resource cost
8 minThrottling mechanism measured★★★★☆
Learning objectives
  • Explain why CFS quota throttling causes latency spikes even when "average CPU is not high", and read the evidence from cpu.stat (nr_throttled / nr_periods, throttled_usec).
  • Read PSI (Pressure Stall Information): some and full in cpu.pressure, memory.pressure and io.pressure.
  • Size gunicorn processes / threads from the container's CPU limit (not the host core count); estimate concurrency with Little's Law and verify with k6 P95/P99 and error rate.
  • Reduce cold starts; estimate Container Apps resource usage and cost in vCPU-seconds / GiB-seconds, and name three cost-reduction levers.
Prerequisites: the USE method from Module 1; Hour 2 (--cpus, --memory); Hour 3 (ACA CPU/memory combinations and scaling). Importance: ★★★★☆

What: CFS quota and throttling

--cpus 0.5 (Compose cpus: "0.5") is written in cgroup v2 as cpu.max = "50000 100000": in every 100 ms period, all threads of this container combined may run for at most 50 ms. Once that is used up, the whole container is paused until the next period - this is throttling.

Multi-threaded / multi-process applications burn through the quota quickly during bursts: for example, with 4 threads computing at once, the 50 ms quota is gone after 12.5 ms, followed by an 87.5 ms wait. Monitoring shows an average CPU of only 40%, yet P99 latency grows by almost 90 ms.

File (in the container, /sys/fs/cgroup/)Meaning
cpu.maxquota period (max 100000 means unlimited)
cpu.statnr_periods periods elapsed, nr_throttled periods throttled, throttled_usec total time paused
cpu.pressurePSI: some avg10=12.5 means that during the last 10 seconds, at least one task was waiting for CPU 12.5% of the time
memory.pressure / io.pressureshare of time stalled on memory reclaim / IO; full means all tasks were waiting
memory.eventsoom, oom_kill, max (times the limit was hit) - direct evidence of OOM

Measured (cgroup quota 25%): a computation needing 0.5 s of CPU went from 0.53 s to 1.96 s of wall-clock time, with 20 of 22 periods throttled.

Why: the "core count" inside a container is a trap

os.cpu_count() and nproc return the host core count and ignore the cpu.max quota. The rule of thumb from the gunicorn docs, 2 × cores + 1, starts 33 processes on a 16-core host while the container has only 0.5 cores - context switching and throttling send latency through the roof, and the 33 processes eat up all the memory too.

How: approach to gunicorn tuning

Workload typeRecommendation
CPU-bound (computation, serialization)processes ≈ CPU limit (rounded up, at least 1–2), no threads
I/O-bound (waiting on the database, external APIs)few processes + threads (--threads 4–8, gthread is used automatically), pool size ≥ thread count (Module 3 case ①)
Mixedlet load testing decide: adjust step by step, watch P95/P99, error rate, nr_throttled, memory

Little's Law: concurrency = throughput × average latency. Target 200 requests/s at an average of 50 ms → you need about 10 concurrent processing units (processes or threads); then check against the CPU quota whether these 10 units get throttled when they compute at the same time.

When: cold starts

When Container Apps has a minimum of 0 replicas, the first request has to wait: scheduling → image pull → process start → module import → ready. Optimizations: min replicas 1 (critical APIs), smaller images, no heavy work at startup (move migrations into jobs, hour 6), lazy-import big dependencies, configure a startup probe so the app isn't declared failed too early.

Cost model (Container Apps Consumption plan)

Billed by vCPU-seconds and GiB-seconds (with different active and idle rates) plus request count; each subscription gets a monthly free grant. Unit prices vary by region and change over time, so go by the Azure pricing page - the calculator in this module only computes resource usage, and you fill in the unit prices. Cost-reduction levers: ① scale to 0 (Workers, jobs); ② pick the right CPU / memory combination instead of "bigger is better"; ③ reduce idle replicas and over-provisioning; ④ eliminate throttling before adding cores - when throttled, adding replicas is often more expensive than adding cores.

Common misconceptions① "Raising the CPU limit always makes it faster" - if the bottleneck is the database or the pool, more CPU does nothing. ② "If average latency is fine, there's no problem" - users feel P95/P99. ③ "Load testing through the gateway tests the application" - the gateway has a 10 r/s/IP rate limit, so you'll measure a pile of 429s. ④ "A larger memory limit is safer" - an oversized limit hides leaks, and on ACA you are billed directly by GiB-seconds.

The throttling timeline

cpu.max = 50000 100000 (0.5 cores), 4 threads running at once Throttled (waiting for next period) 0100 ms (period 2 starts)200 ms 12.5ms
Figure 4-1 4 threads × 12.5 ms = the 50 ms quota is used up at the start of each period, and the remaining 87.5 ms is spent paused

The tuning loop

Baseline testk6: P95 · P99 · errors Read evidencecpu.stat · PSI · memory Change one thingprocs/threads/pool/limit Re-test, comparesame script · duration Record + costtuning report
Figure 4-2 Change only one variable at a time, otherwise you can't attribute the result

Interactive simulator ①: CFS throttling canvas

Choose a preset or drag the sliders: green is running, red is waiting while throttled. The failure presets reproduce "average CPU is low but P99 is high", "processes sized by host core count" and "blind box #6 at 0.1 cores".

Interactive simulator ②: resource usage and cost calculator

CommandDescription
docker exec C cat /sys/fs/cgroup/cpu.max /sys/fs/cgroup/cpu.statquota and throttling statistics (cgroup v2)
docker exec C cat /sys/fs/cgroup/cpu.pressure /sys/fs/cgroup/memory.pressurecontainer-level PSI
cat /proc/pressure/cpuhost-level PSI
docker stats --no-stream --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}'instantaneous CPU and memory
docker update --cpus 1 Cchange the CPU limit live (a Compose-managed container reverts on the next up)
docker run --rm -i --network orders_default -e BASE=http://api:8000 grafana/k6:2.4.0 run - < perf/load.jsload-test api inside the Compose network (bypassing the gateway rate limit)
… grafana/k6:2.4.0 run --summary-export=/dev/stdout --quiet - < perf/load.jsJSON summary, handy for writing reports
time docker run --rm --entrypoint python orders:1.0 -c 'import orders.api'measure import time (part of the cold start)
az containerapp update -g RG -n APP --min-replicas 1avoid the cold start from scaling to 0

perf/load.js (k6, already included in the orders project)

import http from 'k6/http';
import { check, sleep } from 'k6';

const BASE = __ENV.BASE || 'http://api:8000';
export const options = {
  insecureSkipTLSVerify: true,
  stages: [
    { duration: '20s', target: 10 },        // ramp up to 10 virtual users
    { duration: '40s', target: 10 },        // hold
    { duration: '10s', target: 0 },
  ],
  thresholds: {
    http_req_failed: ['rate<0.01'],          // error rate < 1%
    http_req_duration: ['p(95)<300', 'p(99)<800'],
  },
};

export default function () {
  check(http.get(`${BASE}/api/stats`), { 'stats 200': (r) => r.status === 200 });
  check(http.get(`${BASE}/api/chaos/cpu?ms=20`), { 'cpu 200': (r) => r.status === 200 });   // 20 ms of computation
  check(http.post(`${BASE}/api/orders`, JSON.stringify({ item: 'k6', qty: 1 }),
    { headers: { 'Content-Type': 'application/json' } }), { 'order accepted': (r) => r.status === 202 });
  sleep(0.5);
}

Compute the gunicorn process count from the CPU limit (inside the container)

read Q P < /sys/fs/cgroup/cpu.max
[ "$Q" = max ] && CPUS=$(nproc) || CPUS=$(( (Q + P - 1) / P ))
echo "cpu.max=$Q/$P → suggested workers=$CPUS (CPU-bound)"

Hit api:8000 directly inside the Compose network: this bypasses the gateway's 10 r/s rate limit (hour 6 Module 3) and measures the capacity of the application itself. To test the gateway, set BASE to the gateway address and raise the rate limit accordingly or send from multiple IPs.

Baseline load test
bash chaos/blindbox.sh reset
docker run --rm -i --network orders_default -e BASE=http://api:8000 grafana/k6:2.4.0 run --quiet - < perf/load.js 2>&1 | grep -E 'http_req_duration|http_req_failed|iterations\.|✓|✗' | head
✓ 'p(95)<300' p(95)=38ms   ✓ 'p(99)<800' p(99)=71ms
✓ 'rate<0.01' rate=0.00%
http_req_duration..: avg=19ms  min=2ms  med=21ms  max=95ms  p(90)=31ms  p(95)=38ms
http_req_failed....: 0.00%   0 out of 1980
iterations.........: 660     9.4/s
Limit to 0.1 cores, load-test again and read the throttling evidence
dc -f chaos/f6.yaml up -d api
docker exec orders-api-1 cat /sys/fs/cgroup/cpu.max
docker run --rm -i --network orders_default -e BASE=http://api:8000 grafana/k6:2.4.0 run --quiet - < perf/load.js 2>&1 | grep -E 'http_req_duration|✗' | head -3
docker exec orders-api-1 sh -c 'grep -E "nr_periods|nr_throttled|throttled_usec" /sys/fs/cgroup/cpu.stat; cat /sys/fs/cgroup/cpu.pressure'
10000 100000
✗ 'p(95)<300' p(95)=1.92s
http_req_duration..: avg=812ms … p(95)=1.92s
nr_periods 702
nr_throttled 655
throttled_usec 58123456
some avg10=88.41 avg60=61.20 avg300=17.03 total=…
full avg10=85.97 avg60=59.11 avg300=16.50 total=…

93% of periods throttled, PSI some at 88%: CPU is severely short. The mechanism was measured in a hybrid cgroup v1/v2 environment (25% quota: 0.5 s of CPU work took 1.96 s, 20 of 22 periods throttled).

Tune and compare
bash chaos/blindbox.sh reset          # back to cpus 0.5, -w 2
# experiment: for I/O-heavy endpoints use 1 process + 4 threads (pool 5 ≥ threads 4)
cat > /tmp/tune.yaml <<'EOF'
services:
  api:
    command: ["gunicorn", "-b", "0.0.0.0:8000", "-w", "1", "--threads", "4", "--timeout", "25", "--access-logfile", "-", "orders.api:app"]
EOF
dc -f /tmp/tune.yaml up -d api
docker run --rm -i --network orders_default -e BASE=http://api:8000 grafana/k6:2.4.0 run --quiet - < perf/load.js 2>&1 | grep -E 'http_req_duration'
docker stats --no-stream --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}' | grep api

The override file replaces command. You can also append arguments via the GUNICORN_CMD_ARGS environment variable (that's what chaos/f1 and f2 do), but command-line arguments take precedence: -w 2 in CMD overrides any --workers there, so to change the process count you must change command. Enter each result (P95, P99, error rate, memory, nr_throttled) into the tuning report table of the capstone lab.

Measure the cold start
time docker run --rm --entrypoint python orders:1.0 -c 'import orders.api' 2>/dev/null
docker image ls orders:1.0 --format '{{.Size}}'
real	0m1.6s
245MB

Import time includes loading dependencies such as Flask, psycopg and the Azure SDK. On Azure, add the time for image pull and scheduling. Cleanup: bash chaos/blindbox.sh reset; rm /tmp/tune.yaml.

Case 1: "CPU is only at 30%, so why is P99 2 seconds?"

Problem: a Java service limited to 2 cores showed an average CPU of 30% in monitoring, but a P99 latency of 2 seconds. The JVM created lots of GC and worker threads based on the host's 64 cores; each GC burned through the quota within a few milliseconds, after which the whole container was throttled, with nr_throttled/nr_periods as high as 40%. Approach: set -XX:ActiveProcessorCount=2 (newer JVMs already detect cgroup limits) and reduce thread counts; raise the CPU limit somewhat for latency-sensitive services. Limitation: the same applies to Python / gunicorn - set concurrency by quota, not by host core count.

Case 2: the money saved by scaling to 0 is "paid back" in cold starts

Problem: a team set every API to min replicas 0; the first request at night took 8 seconds, and mobile client timeout retries led to duplicate orders. Approach: user-facing APIs keep min replicas 1, Workers and scheduled jobs scale to 0; the order endpoint already has an idempotency key (hour 6), so retries don't charge twice. Limitation: min replicas 1 incurs idle charges - evaluate it with the calculator.

What the same problems look like on Azure

TopicHow it's done on Container Apps
CPU / memorythe Consumption plan uses fixed combinations (0.25 vCPU / 0.5 GiB … 4 vCPU / 8 GiB, hour 3); set the gunicorn process count by vCPU
Throttling evidencethe CpuUsage metric is near the limit while latency rises; you can also read /sys/fs/cgroup/cpu.stat inside the container (az containerapp exec)
Cold start--min-replicas 1; keep the image in an ACR in the same region; reduce startup work
Scalingthe HTTP concurrency rule (default 10) should match gunicorn's concurrency capacity: 2 processes × 4 threads ≈ 8 → --scale-rule-http-concurrency 8
Costscale Workers / jobs to 0; idle replicas are billed at the lower idle rate; view costs grouped by resource in Cost Management
az containerapp update -g $RG -n ca-orders-api --min-replicas 1 --max-replicas 5 \
  --scale-rule-name http --scale-rule-type http --scale-rule-http-concurrency 8 \
  --set-env-vars GUNICORN_CMD_ARGS="--threads 4 --timeout 25" DB_POOL_SIZE=4

Watch the connection budget: DB_POOL_SIZE=4 × 2 processes × 5 replicas = 40, which already exceeds the 35 user connections of B1ms - you must also adjust the replica maximum or the database tier (hour 6 Module 2).

Common errors and fixes

Load test produces lots of 429 Too Many Requests

Cause: you hit the gateway's rate limit (10 r/s/IP). Fix: when load-testing the application itself, connect directly to api:8000 inside the Compose network.

cat: /sys/fs/cgroup/cpu.stat: No such file or directory

Cause: the host uses cgroup v1 (older systems). Fix: in v1 the file is /sys/fs/cgroup/cpu/cpu.stat (field throttled_time is in nanoseconds), and the quota is in cpu.cfs_quota_us. Ubuntu 22.04+ uses v2 by default.

No cpu.pressure file

Cause: the kernel has PSI disabled (CONFIG_PSI) or was booted with psi=0. Ubuntu enables it by default.

Exited (137) / OOMKilled=true after raising workers

Cause: each gunicorn process takes about 50–80 MB (measured in this project: 3 processes ≈ 180 MB RSS combined). Fix: check the memory limit before adding processes; use threads instead of processes for I/O-bound work; confirm with the oom_kill count in memory.events.

k6 reports dial tcp: lookup api … no such host

Cause: the k6 container did not join the Compose network, or the network name is not orders_default. Fix: confirm the network name with docker network ls | grep orders and pass it to --network.

Command-line exercises
1. Compute the throttling ratio of orders-api-1 (throttled periods / total periods, as a percentage).
docker exec orders-api-1 awk '/^nr_periods/{p=$2} /^nr_throttled/{t=$2} END{printf "%.1f%%\n", p?100*t/p:0}' /sys/fs/cgroup/cpu.stat
2. Export k6's P95, P99 and error rate as one line of JSON.
docker run --rm -i --network orders_default -e BASE=http://api:8000 grafana/k6:2.4.0 run --summary-export=/dev/stdout --quiet - < perf/load.js 2>/dev/null \
  | jq -c '{p95: .metrics.http_req_duration["p(95)"], p99: .metrics.http_req_duration["p(99)"], fail: .metrics.http_req_failed.value}'
Scenario analysis
api is limited to 1 core with -w 4, P99 is 800 ms; nr_throttled/nr_periods is 35%, PSI cpu some is 25%, memory is normal. Product requires P99 < 300 ms. Which two changes would you try first? What are the risks of each?

① Reduce the number of processes computing at once (-w 2, with --threads for the I/O part): lowers burst concurrency and reduces throttling; the risk is lower throughput on CPU-bound endpoints, which you need to confirm with a load test. ② Raise the CPU limit to 2 cores or scale out horizontally to 2 replicas: removes throttling directly; the risks are higher cost (vCPU-seconds double) and the database connection budget (replicas × processes × pool). Change only one thing at a time, and record P95/P99, error rate, throttling ratio and the change in cost.

Verified teaching videos

▶
Linux Performance Tools, Brendan Gregg, part 2 of 2 — Brendan Gregg
English · benchmarking, tuning and static performance tools; the methodology applies to container load testing and tuning

Official documentation

Video storyboard script (about 70 seconds)

Shot 1 · 0–25s
Visual: a 100 ms time grid; four green progress bars all finish in the first 12.5 ms, and everything after turns red.
Narration: Once the quota is used up, the whole container waits for the next period.
Shot 2 · 25–50s
Visual: on the dashboard, "average CPU 40%" sits calmly, while the P99 curve next to it keeps spiking; the nr_throttled number in cpu.stat climbs rapidly.
Narration: Averages lie; throttling counters and pressure stalls don't.
Shot 3 · 50–70s
Visual: the calculator converts vCPU-seconds and GiB-seconds into a monthly bill, and three levers light up in turn: scale to 0, right-sized resources, eliminate throttling.
Narration: Measure, change, measure again, and write every step into the tuning report.
or score ≥ 70% on the "Quiz" tab

Module 5 · Scaling Builds: Builder Drivers, Remote Builders, Reproducible Builds and Bake Matrices

29:00 – 36:00 · Faster (standalone / remote / cloud builders), more trustworthy (two builds, one digest), less hassle (one target expands into many variants)
7 minbuildx 0.39 · BuildKit 0.35Bake --print measured★★★★☆
Learning objectives
  • Tell apart the five buildx builder drivers (docker, docker-container, kubernetes, remote, cloud), know when you need a remote builder (lots of memory, native arm64, team sharing) and how mTLS is configured.
  • Use build records (docker buildx history) to diagnose "why is the build slow / why did it fail", and manage how much cache a builder uses.
  • Use SOURCE_DATE_EPOCH + rewrite-timestamp=true, base images pinned by digest and locked dependencies to make reproducible builds, and verify with two --no-cache builds that the digests match.
  • Build several variants with one command using a Bake matrix, and review the expansion with --print.
Prerequisites: Hour 5 Module 2 (cache backends registry / gha / local, mode=max, multi-platform and Bake basics) - not repeated here; this module covers only the scaling part. Importance: ★★★★☆

What: the builder driver decides "where the build runs"

DriverDescriptionGood forWatch out
dockerBuildKit built into dockerd (default)Everyday local builds; results go straight into the local image storeWith the classic image store, cache export types are limited (hour 5 Module 2)
docker-containerRuns a standalone BuildKit in a container; can point at a remote Docker contextMulti-platform, all cache export types, isolated from the host; pinned BuildKit versionResults don't go into the local image store by default; you need --load or --push
kubernetesRuns BuildKit Pods in a cluster (multiple replicas, scheduling by architecture)Team sharing, scalable; native builds on arm64 nodesNeeds cluster permissions; Pod resource limits determine build speed
remoteConnects to a buildkitd you run yourself (TCP + mTLS, or a Unix socket)Big-memory / many-core build machines, native ARM build machinesYou manage certificates and network exposure yourself; expose it only on a private network
cloudDocker Build Cloud hosted buildersTeam-shared cache, native multi-arch, no machines to maintainNeeds a Docker subscription; the source context is uploaded

Why: why build "away from the laptop"

At scale, the root cause of slow builds is usually not the Dockerfile but the machine and where the cache lives: CI runners are thrown away after each job (hour 5 solved this with a registry cache), arm64 under QEMU is 5–10× slower (solved by native builders), compiling dependencies maxes out a 7 GB runner (solved by a big-memory remote builder), and every developer builds from scratch on their own (solved by a shared builder). A remote builder moves all of these problems off developers' machines at once.

How: build records - the builder's "black box"

BuildKit keeps a record for every build: status, duration, logs for each step, cache hits, errors and an OpenTelemetry trace. docker buildx history ls / inspect / logs / trace / export can answer "which step was slow, why didn't it hit the cache, what is the full log of the failure" after the build has finished (even after importing it on another machine). The builder's own cache grows too: check it with docker buildx du and clean it with docker buildx prune --filter until=72h.

Reproducible builds

Building the same source twice yields the same digest - anyone can verify that "this image really comes from this commit", and it also makes caching and signing more reliable (the supply chain from hour 5). The main sources of non-determinism and their fixes:

SourceFix
Timestamps (image config created, history, index annotations, mtime of files in layers)SOURCE_DATE_EPOCH (buildx ≥ 0.10 automatically passes the environment variable of the same name as a build arg) + the exporter option rewrite-timestamp=true (BuildKit ≥ 0.13) to rewrite file times in layers
Base image tag driftPin by digest FROM python:3.13-slim@sha256:…, with Dependabot / Renovate opening update PRs
Dependency version driftLock versions and verify hashes (pip install --require-hashes)
Timestamps in .pycDeclare ARG SOURCE_DATE_EPOCH in the stage; once it is visible in RUN, Python's py_compile switches to hash-based .pyc
apt-get fetching the latest packages of the dayUse a snapshot mirror (e.g. snapshot.debian.org) or accept that this layer is not reproducible
Attestations (provenance contains the build time and invocation parameters)Compare with --provenance=false, or compare only the platform image manifest digest
BuildKit version differencesThe exporter option compatibility-version pins the assembly behavior that affects the digest (currently 30; 20 corresponds to the historical behavior of v0.15–v0.31)

The Dockerfile frontend also supports the special value SOURCE_DATE_EPOCH=context: for a Git context it takes the commit time; for a local directory context it is ignored (left unset).

When: Bake matrices

A matrix in docker-bake.hcl expands one target into several (e.g. one image each for Python 3.12 and 3.13), built in parallel with a shared cache; name uses an expression to generate unique target names, and the original target name automatically becomes a group containing all variants. Note: docker buildx bake also reads compose.yaml by default, and this project's compose needs .env variables, so pass -f docker-bake.hcl explicitly (behavior measured in this lesson).

Common misconceptions① "Remote builders are faster, so put everything there" - the context has to be uploaded over the network, and a large context (no proper .dockerignore) cancels out the gain. ② "Reproducible = use --no-cache" - --no-cache is only a way to verify; reproducibility comes from pinned inputs. ③ "Adding SOURCE_DATE_EPOCH makes it reproducible" - file times in layers also need rewrite-timestamp=true, and the base image and dependencies must be pinned too.

Shared builders: whoever builds first, everyone else benefits

Dev laptop CI runner Remote BuildKit / Build CloudmTLS · big memory · native arm64persistent local cache + build records Registry cache (hour 5)fallback after a builder rebuild Image: orders:1.1@sha256:…same digest twice = reproducible
Figure 5-1 The builder's persistent cache is fastest; the registry cache is the fallback for when "the builder was replaced"

Reproducible builds: fixed inputs, fixed output

Source: git commit 3f9a2c1 FROM …@sha256 (pinned) Deps: --require-hashes SOURCE_DATE_EPOCH=commit BuildKitrewrite-timestamp=true Build A: sha256:4f1c…e2a9 Build B: sha256:4f1c…e2a9
Figure 5-2 If any input drifts (tag, dependencies, time), the digest changes

Interactive simulator: two builds, same digest?

Pick a scenario and play it. In the success scenario both builds produce the same digest; the failure scenarios show the six most common reasons a build is "not reproducible / won't build" (digests and logs are examples).

Ready.
$ export SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)

Builders

CommandDescription
docker buildx lsBuilders, drivers, nodes and BuildKit versions
docker buildx create --name bk --driver docker-container --use --bootstrapStandalone local BuildKit builder
docker buildx create --name bk --driver docker-container --driver-opt image=moby/buildkit:v0.35.0 --bootstrapPin the BuildKit version
docker context create buildvm --docker host=ssh://azureuser@buildvm → docker buildx create --name bvm --driver docker-container buildvmRun the builder on another host's Docker (over SSH)
docker buildx create --name remote --driver remote --driver-opt cacert=…,cert=…,key=…,servername=… tcp://buildhost:1234Connect to a remote buildkitd (mTLS)
docker buildx create --name k8s --driver kubernetes --driver-opt replicas=2,namespace=buildkitBuildKit Pods in Kubernetes
docker buildx create --driver cloud ORG/BUILDERDocker Build Cloud

Build records and cache usage

CommandDescription
docker buildx history lsRecent build records (status, duration)
docker buildx history inspect REF / history logs REFDetails of one build (cache hits, errors) and its full log
docker buildx history trace REFThe OpenTelemetry trace of that build
docker buildx history export REF -o build.dockerbuildExport as a build bundle that Docker Desktop can import, to hand to a colleague for analysis
docker buildx du --builder bk / docker buildx prune --builder bk --filter until=72hBuilder cache usage / cleanup

Reproducibility and Bake

CommandDescription
export SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)Use the commit time as the build time (buildx passes it as a build arg automatically)
--output type=image,name=X,push=true,rewrite-timestamp=trueRewrite file times in layers to SOURCE_DATE_EPOCH
--metadata-file meta.json → jq -r '."containerimage.digest"' meta.jsonRecord and compare digests
docker buildx bake -f docker-bake.hcl --printShow the matrix expansion (no build)
docker buildx bake -f docker-bake.hcl appBuild the app group (the 2 variants from the matrix expansion)
docker buildx bake -f docker-bake.hcl --set '*.platform=linux/arm64' appTemporarily override an attribute on all targets

docker-bake.hcl for orders (expansion verified with buildx 0.38 --print)

variable "TAG" { default = "dev" }
variable "SOURCE_DATE_EPOCH" { default = "0" }   # in CI set to $(git log -1 --pretty=%ct)

group "default" { targets = ["app", "web"] }

target "_common" {
  args      = { SOURCE_DATE_EPOCH = SOURCE_DATE_EPOCH }
  platforms = ["linux/amd64"]
  labels    = { "org.opencontainers.image.source" = "https://github.com/yourname/orders" }
}

target "app" {
  inherits = ["_common"]
  name     = "app-py${replace(py, ".", "")}"
  matrix   = { py = ["3.12", "3.13"] }
  context  = "app"
  args     = { PYTHON_VERSION = py }
  tags     = ["orders:${TAG}-py${py}"]
}

target "web" {
  inherits = ["_common"]
  context  = "web"
  tags     = ["orders-web:${TAG}"]
}
FROM python:${PYTHON_VERSION}-slim AS builder
# hour 7: reproducible build. Once declared it is visible in RUN; py_compile switches to hash-based .pyc
ARG SOURCE_DATE_EPOCH
Bake matrix
docker buildx bake -f docker-bake.hcl --print 2>/dev/null | jq -c '.group, (.target | to_entries[] | {k:.key, args:.value.args, tags:.value.tags})'
docker buildx bake -f docker-bake.hcl app
docker image ls orders --format '{{.Tag}}\t{{.Size}}' | grep py
{"app":{"targets":["app-py312","app-py313"]},"default":{"targets":["app","web"]}}
{"k":"app-py312","args":{"PYTHON_VERSION":"3.12","SOURCE_DATE_EPOCH":"0"},"tags":["orders:dev-py3.12"]}
{"k":"app-py313","args":{"PYTHON_VERSION":"3.13","SOURCE_DATE_EPOCH":"0"},"tags":["orders:dev-py3.13"]}
{"k":"web","args":{"SOURCE_DATE_EPOCH":"0"},"tags":["orders-web:dev"]}
dev-py3.12	…MB
dev-py3.13	…MB
Reproducible build: build twice, compare digests
docker buildx create --name repro --driver docker-container --driver-opt image=moby/buildkit:v0.35.0 --bootstrap >/dev/null
export SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct 2>/dev/null || date -d 2026-11-15 +%s)
for i in 1 2; do
  docker buildx build --builder repro --no-cache --provenance=false \
    --output type=oci,dest=/tmp/web-$i.tar,rewrite-timestamp=true \
    --metadata-file /tmp/meta-$i.json web >/dev/null 2>&1
  jq -r '."containerimage.digest"' /tmp/meta-$i.json
done
sha256:4f1c…e2a9
sha256:4f1c…e2a9          ← identical = reproducible

The web image only has COPY, so it is the easiest to make reproducible. Repeat the experiment on the app image; if the digests differ, compare the two OCI bundles with a tool such as diffoci to find the differing layer (usually files installed by pip). Only after the base image is pinned by digest do results stay stable over time. --no-cache guarantees the second run is a real rebuild; exporting SOURCE_DATE_EPOCH as an environment variable is enough, since buildx passes it as a build arg automatically.

Build records: which step is slowest
docker buildx history ls --builder repro | head -4
REF=$(docker buildx history ls --builder repro | awk 'NR==2 {print $1}')      # ID of the newest record
docker buildx history inspect --builder repro "$REF" | head -20
BUILD ID                    NAME   STATUS     CREATED AT       DURATION
qk3x9…                      web    Completed  1 minute ago     4.1s
p8m2a…                      web    Completed  1 minute ago     4.3s
…
Name:           web
Status:         Completed
Duration:       4.1s
Build Steps:    6/6 (0% cached)
…

Both --no-cache builds have a 0% cache hit rate, as expected. When investigating "CI got slower" day to day, compare the inspect output of a fast and a slow build, and look first at the cache hit rate and the slowest step. For the fields in the list and in inspect, go by docker buildx history ls --help and your actual output.

Remote builder (optional: needs a second Linux machine)
docker context create buildvm --docker host=ssh://azureuser@buildvm
docker buildx create --name bvm --driver docker-container buildvm --bootstrap
docker buildx ls | grep -A1 bvm
time docker buildx build --builder bvm -t orders:remote-test --load app
bvm             docker-container
 \_ bvm0         \_ buildvm        running   v0.35.0    linux/amd64, linux/amd64/v2, linux/386
…
real	0m48.2s

The build runs on buildvm, and --load sends the result back to your machine. In production it is more common to use the remote driver to connect to an mTLS-protected buildkitd, or to create a node on an arm64 machine and add it to the same builder with docker buildx create --append for native multi-arch. Cleanup: docker buildx rm repro bvm; docker context rm buildvm; rm -f /tmp/web-*.tar /tmp/meta-*.json.

Case 1: CI builds from 14 minutes to 3 minutes

Problem: a team's CI built from scratch on a brand-new runner every time (the dependency layer that compiles C extensions took 10 minutes). Approach: after introducing a mode=max registry cache (Hour 5 Module 2), that layer hit the cache directly when dependencies hadn't changed; then Bake built the 3 services in parallel, bringing the total down to 3 minutes. Later the weekly base image tag updates kept invalidating the cache, so they pinned the base image by digest with Dependabot opening a PR every week - the cache became stable and updates controlled. Limitation: the registry cache incurs storage costs and must be covered by a retention policy.

Case 2: arm64 from 40 minutes to 6 minutes

Problem: to use Graviton / Ampere instances, the team turned on multi-platform builds, and installing arm64 dependencies under QEMU took 40 minutes. Approach: they ran buildkitd on an arm64 VM (mTLS, exposed only on the private network) and added it to the builder as an arm64 node with docker buildx create --append, so both amd64 and arm64 build natively. Limitation: the builder is a long-running resource that needs patching, disk monitoring and certificate rotation.

Case 3: third-party verification that "the image comes from this commit"

Problem: a customer required independent verification that the delivered image matches the open-source code. Approach: CI uses SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct), a pinned base image digest, hash-locked dependencies and rewrite-timestamp=true; the release notes give the build command and the pinned BuildKit version, and the customer's local rebuild yields the same platform manifest digest. Limitation: system packages installed with apt need a snapshot mirror; attestations such as provenance are excluded from the comparison.

On Azure

OptionDescription
az acr build (ACR Tasks)Builds in Azure with no local Docker needed (hour 3); suits simple pipelines
Self-hosted remote BuildKitRun buildkitd on Azure VMs (including Ampere arm64 sizes) with mTLS, exposed only on a private network
kubernetes driver on AKSSchedule BuildKit Pods by node pool architecture; push to ACR with workload identity
Reproducible + signedPin SOURCE_DATE_EPOCH in CI, and after the build sign the digest with cosign or Notation (Hour 5 Module 6)

Common errors and fixes

ERROR: Cache export is not supported for the docker driver.

Cause: the default docker driver (with the classic image store) doesn't support that cache export type. Fix: docker buildx create --driver docker-container --use, or enable the containerd image store (hour 5 Module 2).

bake fails with an error like required variable DB_PASSWORD is missing a value

Cause: by default bake also reads compose.yaml, which references variables from .env. Fix: specify the file with -f docker-bake.hcl (this behavior was measured in this lesson).

Two builds produce different digests

Check: whether the base image tag was updated and whether dependencies are locked; whether the Dockerfile declares ARG SOURCE_DATE_EPOCH; whether the exporter has rewrite-timestamp=true; whether provenance was included (compare with --provenance=false); whether the two builds used different BuildKit versions. Compare the two OCI bundles with diffoci to locate the differing layer.

Remote builder x509: certificate signed by unknown authority / certificate is valid for …, not …

Cause: cacert and the server certificate are not from the same CA, or servername does not match the certificate SAN. Fix: reissue the server certificate with the correct SAN, and make the client's servername= match it.

Remote builds are slow and the log is stuck at transferring context: 1.2GB

Cause: the context is too large (.git, node_modules, test data are being sent). Fix: improve .dockerignore; if needed, use a Git context (the remote side pulls the code directly).

Builder disk full: no space left on device

Cause: a long-running builder's cache keeps growing. Fix: check usage with docker buildx du, clean up regularly with docker buildx prune --filter until=72h, or set a garbage collection policy in the buildkitd config.

Command-line exercises
1. Using only --print, list every Bake target with its platforms and tags.
docker buildx bake -f docker-bake.hcl --print 2>/dev/null \
  | jq -r '.target | to_entries[] | "\(.key)\t\(.value.platforms | join(","))\t\(.value.tags | join(","))"'
2. Create a docker-container builder pinned to BuildKit v0.35.0 and confirm its version.
docker buildx create --name pinned --driver docker-container --driver-opt image=moby/buildkit:v0.35.0 --bootstrap
docker buildx inspect pinned | grep -i 'buildkit'
Scenario analysis
The team wants to "make every build reproducible". Ranked by return on effort, which three things would you do first?

① Pin base images by digest (lowest cost, biggest payoff, and it also stabilizes the cache); ② lock dependencies + verify hashes (pip --require-hashes / npm ci); ③ in CI export SOURCE_DATE_EPOCH as the commit time and add rewrite-timestamp=true. After that, run "two --no-cache builds + compare the platform manifest digests" as a periodic check; document apt system packages and attestations as known exceptions.

About teaching videos

No verifiable, high-quality video was found that covers current usage of the buildx remote driver, build records and rewrite-timestamp (older videos mostly rely on parameters that have since changed). Below are the official resources and a storyboard script.

Video storyboard (about 70 seconds)

Shot 1 · 0–20s
Visual: a laptop fan roars while an arm64 build progress bar crawls along; cut to a native arm64 build machine in a server room, where the progress bar flies.
Narration: The first step in scaling builds is moving them onto the right machine.
Shot 2 · 20–50s
Visual: two machines build the same commit at the same time; two digests are compared character by character on screen, the last one matches, and a green light comes on. Four input locks (commit, base image, dependencies, timestamp) snap shut one after another.
Narration: Fixed inputs, fixed output.
Shot 3 · 50–70s
Visual: a Bake target fans out like playing cards into two, py3.12 and py3.13, which enter the builder together.
Narration: A matrix turns one declaration into many variants; look at it with --print first, then build.
or score ≥ 70% on the "Quiz" tab

Module 6 · Advanced Networking and Storage

36:00 – 43:00 · Beyond bridge: macvlan / ipvlan, IPv6 dual stack, Engine 29's nftables firewall backend, MTU, and the performance differences between the container layer / volumes / tmpfs
7 minnftables backend is still experimental★★★☆☆
Learning objectives
  • Explain the difference between macvlan and ipvlan, when to use each, and their limits in public-cloud virtual networks; know that from Engine 29 they no longer configure a gateway by default.
  • Create an IPv6 dual-stack network and verify IPv6 traffic between containers; know how ULA addresses relate to ip6tables / nftables rules.
  • Understand Engine 29's experimental nftables backend: how to enable it, the table names, the absence of a DOCKER-USER chain, the IP forwarding requirement, and the changing Swarm restrictions.
  • Recognize the "small requests succeed, large requests hang" MTU problem; choose between the container layer, named volumes, bind mounts or tmpfs based on read/write patterns.
Prerequisites: Hour 1 (bridge, port mapping); Linux hour 6 Module 3 (Chinese) (nftables syntax). Importance: ★★★☆☆ (most applications only use bridge, but when something breaks you need to understand this)

What: macvlan and ipvlan

bridge (default)macvlanipvlan L2 / L3
Container's identity on the physical networkHidden behind the host IP (NAT)Its own MAC + IP, like a real deviceShares the parent NIC's MAC, own IP (L3 mode forwards by routing)
Requirements on network gearNoneThe switch / virtual switch must allow multiple MACs per port (promiscuous mode)No multi-MAC requirement; L3 needs upstream routes pointing to the host
Host ↔ containerWorksCannot talk directly (kernel restriction; needs an extra macvlan sub-interface)L2 likewise cannot talk directly
Typical useAlmost every applicationLegacy systems that must appear on the LAN, monitoring probes, IoT gatewaysSwitches that limit MAC count, large address counts

Change in Engine 29: when the IPAM config of a macvlan or ipvlan-l2 network has no explicit --gateway, the network no longer configures a default gateway (29.0.0 release notes). If you need to reach the outside through them, pass --gateway when creating the network.

Public-cloud limitsAn Azure virtual network only delivers traffic to a VM NIC for the IPs / MACs assigned to that NIC; unregistered MACs are dropped, so macvlan cannot talk to the outside on an Azure VM. ipvlan also requires configuring the container IPs as secondary IPs on the NIC and handling routing. When you need "containers that own VNet IPs" in the cloud, use the platform solution (Azure CNI for AKS, VNet integration for Container Apps). The lab below verifies the behavior inside the VM with a virtual NIC (dummy).

IPv6

docker network create --ipv6 NAME creates a dual-stack network; without --subnet it allocates from the default address pools, and if no IPv6 pool is configured it uses ULA (fd00::/8). ip6tables rules (isolation and port mapping) are enabled by default. The default bridge network needs "ipv6": true and "fixed-cidr-v6" in daemon.json. In Compose, set enable_ipv6: true on the network. IPv6 is only supported by Docker on Linux hosts.

nftables firewall backend (Engine 29, experimental)

  • Enable: daemon.json "firewall-backend": "nftables" (or dockerd --firewall-backend=nftables); on Linux, docker info reports which firewall backend is in use.
  • Docker creates the ip docker-bridges and ip6 docker-bridges tables and owns them completely - do not edit them by hand; edits will be lost.
  • No DOCKER-USER chain: put custom rules in your own table, using a base chain with the same type and hook + a priority to control ordering.
  • Docker does not enable IP forwarding for you: the host needs net.ipv4.ip_forward=1 (for IPv6, net.ipv6.conf.all.forwarding=1).
  • Swarm: the official docs say overlay rules have not been migrated yet and the backend cannot be enabled in Swarm mode; the 29.10.0 (2026-11-16) release notes say an engine using the nftables backend "can now join a Swarm (experimental)". For production Swarm, keeping the iptables backend is still recommended.
  • After switching, most existing iptables rules are removed; if you had previously set the FORWARD policy to DROP, you may need to deal with it by hand.

MTU: "the small ones succeed, the big ones hang"

Container NICs default to MTU 1500. Once the host joins a VPN / tunnel (e.g. 1400), large packets must be fragmented or rely on Path MTU Discovery (PMTUD); if a firewall on the path drops ICMP "fragmentation needed" messages, large packets are black-holed: the handshake succeeds, small requests succeed, and uploads or large responses hang until they time out. Fix: set -o com.docker.network.driver.mtu=1400 on the network (or mtu in daemon.json), and allow ICMP type 3 code 4.

Storage performance

LocationCharacteristicsGood for
Container writable layer (overlayfs / containerd snapshotter)Copy-on-write: the first modification of a large file from the image copies the whole file first; gone when the container is removedSmall temporary files
Named volumeBypasses copy-on-write and writes straight to the host filesystem; managed by DockerDatabases, queue data
Bind mountA host directory; same performance as a volume; you handle permissions / UIDs yourselfMounting source code and config files during development
tmpfsIn memory, fastest, size-limited, lost on restart, counts toward container memorySensitive temporary files, upload buffers (watch the size! blind box fault #8)

Three drivers: hidden behind NAT / own MAC / shared MAC with own IP

bridgemacvlanipvlan L2 eth0 · MAC A · 10.0.0.4 docker0 + NAT/MASQUERADE 172.18.0.2172.18.0.3 eth0 (parent, promiscuous) MAC B192.168.1.21MAC C192.168.1.22 eth0 · MAC A MAC A192.168.1.31MAC A192.168.1.32
Figure 6-1 bridge hides containers behind NAT; macvlan gives each container its own MAC; ipvlan shares the parent interface's MAC

Where the rules live in the two firewall backends

iptables backend (default)filter FORWARD → DOCKER-USER → DOCKER-FORWARD …nat PREROUTING/OUTPUT → DOCKER (DNAT port mapping)nat POSTROUTING → MASQUERADECustom rules: DOCKER-USER chain nftables backend (29, experimental)table ip docker-bridges / ip6 docker-bridgesDocker owns these tables; don't hand-editNo DOCKER-USER: own table + same-hook chain + priorityHost must enable IP forwarding
Figure 6-2 Before switching backends, migrate the rules in DOCKER-USER to your own nftables table

Interactive simulator: how a packet travels

Pick a network scenario and press play: see which stages the packet passes through and where it is rewritten or dropped. The failure scenarios match the real symptoms in this module's "Troubleshooting" tab (example).

Ready.
$ docker network ls
CommandDescription
docker network create -d macvlan --subnet 192.168.1.0/24 --gateway 192.168.1.1 -o parent=eth0 lanmacvlan (bridge mode); from Engine 29 an explicit --gateway is required
… -o parent=eth0.50802.1Q sub-interface (created automatically by Docker)
docker network create -d ipvlan -o ipvlan_mode=l2 -o parent=eth0 --subnet … ipvipvlan L2 (l3 is routed mode)
docker network create --ipv6 v6netDual-stack network (automatic ULA subnet)
docker network inspect v6net -f '{{json .IPAM.Config}}'Show the allocated subnets
docker network create -o com.docker.network.driver.mtu=1400 vpnnetSet the network MTU
docker info | grep -i firewallCurrent firewall backend (Linux)
sudo nft list tables / sudo nft list table ip docker-bridgesRules of the nftables backend
sudo iptables -t nat -S DOCKERPort-mapping rules of the iptables backend
ping -M do -s 1372 HOSTProbe the path MTU without fragmentation (1372 + 28 = 1400)
docker system df -vDisk usage of images, containers and volumes
macvlan / ipvlan (inside the VM, with a virtual NIC)
sudo ip link add dummy0 type dummy && sudo ip link set dummy0 up
docker network create -d macvlan --subnet 192.168.77.0/24 -o parent=dummy0 mv
docker run -d --name m1 --network mv --ip 192.168.77.11 alpine sleep 600
docker run --rm --network mv alpine sh -c 'ip -br link show eth0; ping -c1 -W1 192.168.77.11 | tail -1'
docker exec m1 ip -br link show eth0
ping -c1 -W1 192.168.77.11 | tail -1 || echo "The host cannot reach the macvlan container directly"
docker rm -f m1; docker network rm mv
docker network create -d ipvlan -o ipvlan_mode=l2 --subnet 192.168.78.0/24 -o parent=dummy0 ipv
docker run --rm --network ipv alpine ip -br link show eth0
ip -br link show dummy0
docker network rm ipv; sudo ip link del dummy0
eth0@if5   UP   2e:8a:41:…        ← every macvlan container has a different MAC
1 packets transmitted, 1 packets received, 0% packet loss
eth0@if5   UP   9a:12:7c:…
1 packets transmitted, 0 received, 100% packet loss
The host cannot reach the macvlan container directly
eth0@if5   UP   d6:3b:…:5f        ← MAC of the ipvlan container
dummy0     UNKNOWN  d6:3b:…:5f    ← same as the parent interface

The dummy NIC has no gateway, which fits Engine 29's new "no gateway unless explicitly specified" behavior; containers talk to each other directly within the same subnet.

IPv6 dual-stack network
docker network create --ipv6 v6net
docker network inspect v6net -f '{{range .IPAM.Config}}{{.Subnet}} {{end}}'
docker run -d --name s6 --network v6net nginx:1.29-alpine
docker run --rm --network v6net alpine sh -c 'ip -6 -br addr show eth0; wget -qO- -T2 "http://[$(getent ahostsv6 s6 | head -1 | cut -d" " -f1)]/" | head -c 60'
docker rm -f s6; docker network rm v6net
172.19.0.0/16 fd3a:8b1c:42e7::/64
eth0   UP   fd3a:8b1c:42e7::3/64 fe80::…/64
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!
nftables backend (optional, only on a disposable VM)
# Back up the current config first; the variables below must survive in the same Bash session
backup="/tmp/docker-daemon.json.before-nftables.$$"
had_config=0
if sudo test -f /etc/docker/daemon.json; then sudo cp -a /etc/docker/daemon.json "$backup"; had_config=1; fi
sudo sysctl -w net.ipv4.ip_forward=1
# Merge the setting, keeping any other options already in daemon.json
sudo python3 - <<'PY'
import json
from pathlib import Path
p = Path('/etc/docker/daemon.json')
data = json.loads(p.read_text()) if p.exists() else {}
data['firewall-backend'] = 'nftables'
p.write_text(json.dumps(data, indent=2) + '\n')
PY
sudo systemctl restart docker && docker info 2>/dev/null | grep -i firewall
sudo nft list tables | grep docker
docker run -d --rm --name nft-demo -p 8088:80 nginx:1.29-alpine
sudo nft list table ip docker-bridges | grep -m3 8088
docker stop nft-demo
# Exact restore: put back the original config if there was one; only delete the file if this run created it
if [ "$had_config" = 1 ]; then sudo cp -a "$backup" /etc/docker/daemon.json; sudo rm -f "$backup"; else sudo rm -f /etc/docker/daemon.json; fi
sudo systemctl restart docker
 Firewall Backend: nftables
table ip docker-bridges
table ip6 docker-bridges
		… tcp dport 8088 … dnat to 172.17.0.2:80 …

Go by your actual output for the name of the firewall backend field in docker info; rule details change between versions (experimental feature). Restarting Docker stops running containers (those with a restart policy are brought back up) - after restoring the config, check the orders stack and run dc up -d if needed.

MTU probe (read-only)
docker run --rm alpine sh -c 'cat /sys/class/net/eth0/mtu'
docker run --rm alpine sh -c 'ping -c1 -W2 -M do -s 1472 1.1.1.1 | tail -2; ping -c1 -W2 -M do -s 1372 1.1.1.1 | tail -1'
1500
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 2.1/2.1/2.1 ms
1 packets transmitted, 1 packets received, 0% packet loss

1472-byte payload + 28-byte headers = 1500. When the path MTU is smaller, the first ping reports message too long or gets no reply while the second (1400) succeeds - that is when you set a smaller MTU on the Docker network.

Storage write performance comparison
for t in "container layer|" "named volume|-v perfvol:/data" "tmpfs|--tmpfs /data:size=300m"; do
  n=${t%%|*}; o=${t#*|}
  r=$(docker run --rm $o alpine sh -c 'mkdir -p /data; dd if=/dev/zero of=/data/f bs=1M count=200 conv=fsync 2>&1 | tail -1')
  echo "$n: $r"
done; docker volume rm perfvol >/dev/null
container layer: 209715200 bytes (200.0MB) copied, 1.21 seconds, 165.3MB/s
named volume: 209715200 bytes (200.0MB) copied, 0.98 seconds, 204.1MB/s
tmpfs: 209715200 bytes (200.0MB) copied, 0.09 seconds, 2.2GB/s

Sequential writes of new files differ little; what is really slow in the container layer is "modifying a large file that already exists in the image" (copy-on-write copies the whole file first) and metadata operations on many small files. Always use volumes for databases.

Case 1: an MTU mismatch makes "only large requests fail"

Problem: after a team connected its Docker hosts to a VPN, small requests worked fine, but uploads larger than a few KB hung until they timed out. tcpdump showed large packets being retransmitted over and over: the VPN tunnel MTU was 1400, the Docker network was still 1500, and ICMP "fragmentation needed" messages on the path were dropped by a firewall (PMTUD broken). Approach: create the network with -o com.docker.network.driver.mtu=1400 (or mtu in daemon.json), and allow ICMP type 3 code 4. Limitation: the MTU of an existing network cannot be changed; you must recreate the network and reconnect the containers. "The small ones succeed, the big ones hang" is almost always an MTU problem.

Case 2: containers lose outbound access after switching to nftables

Problem: the security team required nftables everywhere; ops enabled the nftables backend in daemon.json, and after the restart no container could reach the internet. Approach: it turned out Docker's iptables backend had been enabling IP forwarding automatically at startup, and the nftables backend does not; persist net.ipv4.ip_forward=1 in /etc/sysctl.d/, and migrate the allowlist from the old DOCKER-USER chain to a table of your own. Limitation: the feature is still experimental; validate on non-production hosts first.

Case 3: tmpfs "blows up" the container

Problem: to "speed things up", a team switched the upload directory to tmpfs without a size; after one bulk import the container was killed for exceeding its memory limit. Approach: tmpfs writes count toward container memory; set a size on tmpfs, and stream large files directly to object storage instead (hour 6 Module 6). Limitation: a size that is too small causes ENOSPC instead (blind box #8).

On Azure

NeedSolution on Azure
Containers own IPs inside the VNetAKS + Azure CNI; Container Apps environment VNet integration (the environment gets a subnet, apps are reached through an internal load balancer)
IPv6VNets and load balancers support dual stack; for IPv6 support on container platforms, check each service's documentation
Fixed outbound IP / SNATNAT Gateway (Module 3, case ④)
Persistent storageContainer Apps can mount Azure Files (SMB / NFS) volumes; databases use managed services rather than container volumes (hour 6)

Common errors and fixes

macvlan container cannot reach the outside and cannot ping the gateway

Cause: the parent interface's network does not allow multiple MACs (cloud VNets, some Wi-Fi, switches with port security enabled); or under Engine 29 the network was created without --gateway. Fix: switch to ipvlan or use a physical network that supports it; specify the gateway explicitly.

The host cannot reach a macvlan container

Cause: a kernel restriction. Fix: create a macvlan sub-interface on the host and configure a route, or also attach the container to a bridge network.

Containers lose outbound access after enabling nftables

Cause: IP forwarding is not enabled; or existing nftables / iptables rules on the host (e.g. a FORWARD policy of DROP) are blocking traffic. Fix: check sysctl net.ipv4.ip_forward and nft list ruleset.

Existing DOCKER-USER rules stop working after the switch

Cause: the nftables backend has no DOCKER-USER chain. Fix: migrate the rules to your own nftables table (same hook, suitable priority).

IPv6 containers cannot reach external IPv6

Cause: ULA addresses need NAT66, or the host itself has no IPv6 egress. Fix: verify the ip6tables / nftables masquerade rules and the host's IPv6 routes; or use a globally routable prefix and configure upstream routing.

ping: sendto: Message too long / large requests hang

Cause: the path MTU is smaller than the container NIC's MTU. Fix: set a smaller MTU on the Docker network and allow ICMP fragmentation-needed messages.

Command-line exercises
1. Create a user network with MTU 1400 and confirm it inside a container.
docker network create -o com.docker.network.driver.mtu=1400 vpnnet
docker run --rm --network vpnnet alpine cat /sys/class/net/eth0/mtu
2. List the driver, IPv6 flag and subnets of every network.
docker network ls -q | xargs docker network inspect -f '{{.Name}}	{{.Driver}}	ipv6={{.EnableIPv6}}	{{range .IPAM.Config}}{{.Subnet}} {{end}}'
Scenario analysis
A legacy monitoring probe requires "its own IP on the LAN". One of your Docker hosts is in the data center and one is in Azure. What do you do for each?

Data center: after confirming the switch port allows multiple MACs, use macvlan (specify --gateway; the host needs an extra sub-interface to reach the container); if MACs are limited, use ipvlan L2. Azure: macvlan is not viable (the VNet drops unregistered MACs); use ipvlan and configure the container IP as a secondary IP on the NIC, or reconsider - switching to a platform solution (AKS + Azure CNI, or running the probe directly on the VM) is usually simpler.

Verified teaching videos

▶
Docker networking is CRAZY!! (you NEED to learn it) — NetworkChuck
English · includes macvlan and ipvlan L2/L3 demos (predates the nftables backend and Engine 29's gateway change)
▶
Docker Networking Tutorial, ALL Network Types explained! — Christian Lempa
English · comparison of network types

Official documentation

Video storyboard (about 60 seconds)

Shot 1 · 0–20s
Visual: three containers each wear a different kind of "ID card": bridge hides behind the host, macvlan holds up its own MAC, ipvlan borrows the host's MAC.
Narration: The driver decides what a container "looks like" on the network.
Shot 2 · 20–40s
Visual: a cloud switch checks a MAC list like a doorman and keeps macvlan's packets out.
Narration: Public clouds only accept registered addresses, so layer-2 tricks often don't work in the cloud.
Shot 3 · 40–60s
Visual: a large packet gets stuck at the mouth of a narrow tunnel while small packets pass; after lowering the network MTU, the large packet is cut to a fitting size.
Narration: Small ones succeed, big ones hang: check the MTU first.
or score ≥ 70% on the "Quiz" tab

Module 7 · Developer Experience + GPU / AI Workloads

43:00 – 50:00 · The end of "works on my machine" (Dev Containers, Testcontainers), plus using GPUs in containers (NVIDIA Container Toolkit, --gpus, CDI)
7 minTestcontainers test logic measuredGPU lab optional★★★☆☆
Learning objectives
  • Use devcontainer.json so that anyone who opens the repo gets the same development environment (including dependency services such as the database), and use it from the command line / CI with @devcontainers/cli.
  • Write integration tests against a real PostgreSQL with Testcontainers, and know the new 4.x import path and the networking trap when running inside a dev container.
  • Understand what a GPU container is made of: host driver, NVIDIA Container Toolkit, --gpus and CDI (--device nvidia.com/gpu=all), and what changed for CDI in Engine 28 / 29; be able to pinpoint the four most common GPU errors.
Prerequisites: Hour 6 (the orders compose.yaml and migrations); Hour 2 (multi-stage builds). Importance: ★★★☆☆

What: Dev Containers

An open specification (containers.dev): the repo's .devcontainer/devcontainer.json describes the development environment - base image, "features" to install, dependency services to start, port forwarding, commands to run after creation, and editor extensions. It is supported by VS Code, GitHub Codespaces, JetBrains and the command-line tool @devcontainers/cli (latest 0.90.0 as of 2026-11).

This project reuses the compose.yaml from hour 6: dockerComposeFile layers on a dev service (the official Python dev image, with the source mounted at /workspaces/orders), and runServices starts only dev and the dependencies (postgres, redis, rabbitmq, azurite), not api / worker - those you run under the debugger inside the dev container.

What: Testcontainers

Start real dependency containers from your test code; they are deleted automatically when the tests finish. Compared with SQLite or mock objects, it exercises the real SQL dialect, constraints, transactions and locking behavior (e.g. the ON CONFLICT and CHECK constraints from hour 6). In the Python 4.x line (latest 4.15.0 as of 2026-11) the module's new import path is testcontainers.community.postgres (the old path testcontainers.postgres emits a deprecation warning - verified for this course); driver=None returns a postgresql:// URL without an SQLAlchemy driver name, which psycopg 3 can use directly.

What: what a GPU container is made of

LayerComponent
HostNVIDIA GPU + driver (installed only on the host, never inside the container)
Runtime integrationNVIDIA Container Toolkit (latest v1.20.2 as of 2026-11-17): injects the driver libraries and device nodes into the container
Request method 1: --gpusdocker run --gpus all. Since Engine 29.2, --gpus requests for NVIDIA devices are injected via CDI whenever possible; without a CDI spec they still go through the NVIDIA runtime configured by nvidia-ctk runtime configure --runtime=docker
Request method 2: CDIContainer Device Interface: a standard device description file (/var/run/cdi/nvidia.yaml). Docker Engine enables CDI by default since 28.3.0; the nvidia-cdi-refresh systemd service in Toolkit 1.18.0+ regenerates the spec automatically when the Toolkit or driver is installed / upgraded, and on reboot. Usage: docker run --device nvidia.com/gpu=all
ImageThe CUDA runtime libraries live in the image (e.g. nvidia/cuda:*-runtime-*, PyTorch images); the version must be compatible with the host driver

When: when to use them

Dev Containers: onboarding new people, multi-language / multi-version toolchains, environments that must match CI. Testcontainers: any integration test that depends on a database, message queue or object storage (CI's ubuntu runners come with Docker). GPU containers: model inference services, batch training / inference jobs. On Azure you can use NC / ND series VMs, AKS GPU node pools, or Container Apps serverless GPUs (workload profiles, available by region and quota). For running models during local development, Docker Desktop ships the NVIDIA Container Toolkit and Docker Model Runner, and the Compose spec also has a top-level models element - these belong to the Desktop developer experience and are not covered in this course.

Common misconceptions① "The GPU driver has to go into the image" - the driver lives only on the host; the image contains only the CUDA runtime. ② "Testcontainers is Java-only" - Python, Go, .NET and Node all have official implementations. ③ "Running Testcontainers inside a dev container is the same as on my machine" - with docker-outside-of-docker, the new container's port mappings are on the host, and localhost inside the dev container can't reach them. ④ "After a driver upgrade, containers just work" - the CDI spec may be stale and needs refreshing (or rely on nvidia-cdi-refresh).

Left: dev container and integration tests; right: the layers of a GPU container

Dev Container (compose project) devVS Code Server · debugger postgresredis rabbitmqazurite pytest + TestcontainersTemp postgres:17 via host Docker, deleted after tests GPU host NVIDIA GPU + host driver NVIDIA Container Toolkit · CDI spec /var/run/cdi/nvidia.yaml Container: CUDA runtime + model (--gpus all / --device nvidia.com/gpu=all)
Figure 7-1 The dev container reuses the production compose dependencies; a GPU container carries only the runtime, and the host injects the driver via the Toolkit / CDI

The Testcontainers lifecycle

pytest session startsfixture(scope=session) Start postgres:17random host port + wait ready Migrate and testreal constraints / ON CONFLICT with block endsstop and delete container Safety-net cleanupRyuk / label filter
Figure 7-2 If the test process crashes, the Ryuk helper container deletes leftover containers (it can be disabled with an environment variable; usually kept on in CI)

Interactive simulator: the startup chain from tests to GPU

Pick a scenario and press play. Success scenarios show the full startup steps for Testcontainers and for a GPU container; failure scenarios stop at the most common error (example output).

Ready.
$ cd ~/orders/app
CommandDescription
npm i -g @devcontainers/cli@0.90.0Dev Containers CLI (pinned version)
devcontainer up --workspace-folder .Create and start from devcontainer.json
devcontainer exec --workspace-folder . pytest -q app/testsRun a command inside the dev container (works in CI too)
pip install -r app/requirements-dev.txt && (cd app && pytest -q)Run the Testcontainers tests directly on the VM
sudo nvidia-ctk runtime configure --runtime=docker && sudo systemctl restart dockerConfigure the NVIDIA runtime for Docker (edits daemon.json)
nvidia-ctk cdi listList CDI device names
sudo systemctl restart nvidia-cdi-refresh.serviceRegenerate the CDI spec (Toolkit 1.18+)
docker info | grep -A3 -i cdiCDI spec directories and devices Docker discovered (Engine 28.3+)
docker run --rm --gpus all ubuntu nvidia-smiVerify the GPU is usable
docker run --rm --device nvidia.com/gpu=all ubuntu nvidia-smi -LRequest GPUs the CDI way

.devcontainer/devcontainer.json (already included in the orders project)

{
  "name": "orders-dev",
  "dockerComposeFile": ["../compose.yaml", "compose.devcontainer.yaml"],
  "service": "dev",
  "runServices": ["dev", "postgres", "redis", "rabbitmq", "azurite"],
  "workspaceFolder": "/workspaces/orders",
  "shutdownAction": "stopCompose",
  "features": {
    "ghcr.io/devcontainers/features/docker-outside-of-docker:1": {}
  },
  "forwardPorts": [8000, 15672],
  "postCreateCommand": "pip install --user -r app/requirements-dev.txt",
  "customizations": {
    "vscode": { "extensions": ["ms-python.python", "ms-azuretools.vscode-containers"] }
  }
}

app/tests/test_db.py (test logic verified against a local PostgreSQL: 3 passed)

import os
import psycopg
import pytest
from testcontainers.community.postgres import PostgresContainer   # new 4.x path (old path deprecated)


@pytest.fixture(scope="session")
def db_url():
    with PostgresContainer("postgres:17", driver=None) as pg:      # driver=None → postgresql://…
        os.environ["DATABASE_URL"] = pg.get_connection_url()
        yield os.environ["DATABASE_URL"]


def test_migrations_are_idempotent(db_url):
    from orders import config, migrate
    config.DATABASE_URL = db_url
    migrate.main()
    migrate.main()                                                  # second run must not re-apply anything
    with psycopg.connect(db_url) as conn:
        versions = [r[0] for r in conn.execute("SELECT version FROM schema_migrations ORDER BY 1")]
    assert versions == ["001_init.sql", "002_expand_customer_email.sql"]


def test_idempotency_key_prevents_duplicates(db_url):
    sql = """INSERT INTO orders (item, qty, idempotency_key) VALUES ('book', 1, 'k-1')
             ON CONFLICT (idempotency_key) DO NOTHING RETURNING id"""
    with psycopg.connect(db_url) as conn:
        first = conn.execute(sql).fetchone()
        second = conn.execute(sql).fetchone()
        count = conn.execute("SELECT count(*) FROM orders WHERE idempotency_key='k-1'").fetchone()[0]
    assert first is not None and second is None and count == 1


def test_qty_must_be_positive(db_url):
    with psycopg.connect(db_url) as conn, pytest.raises(psycopg.errors.CheckViolation):
        conn.execute("INSERT INTO orders (item, qty) VALUES ('bad', 0)")

Requesting GPUs in Compose

services:
  inference:
    image: nvidia/cuda:12.6.3-base-ubuntu24.04
    command: nvidia-smi
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: all            # or device_ids: ["0"]
              capabilities: [gpu]
Testcontainers integration tests
python3 -m venv ~/.venvs/orders && . ~/.venvs/orders/bin/activate
pip install -q -r requirements-dev.txt
pytest -q tests
docker ps -a --filter ancestor=postgres:17 --format '{{.Names}}' | wc -l
...                                                                      [100%]
3 passed in 6.21s
0          ← the container was deleted after the tests
Dev Container (command-line way)
sudo apt-get install -y nodejs npm && sudo npm i -g @devcontainers/cli@0.90.0
devcontainer up --workspace-folder . | tail -1
devcontainer exec --workspace-folder . python -c "import socket; print(socket.gethostbyname('postgres'))"
devcontainer exec --workspace-folder . bash -lc 'cd app && CHAOS_ENABLED=1 python -m flask --app orders.api run -p 8000 & sleep 3; curl -s localhost:8000/healthz'
docker compose ls
{"outcome":"success","containerId":"…","remoteUser":"vscode","remoteWorkspaceFolder":"/workspaces/orders"}
172.20.0.3
ok
NAME                    STATUS       CONFIG FILES
orders                  running(9)   …/compose.yaml,…/chaos/base.yaml
orders_devcontainer     running(5)   …/compose.yaml,…/.devcontainer/compose.devcontainer.yaml

GUI way: install the Dev Containers extension in VS Code, open the folder and choose "Reopen in Container". The Compose project name is generated by the tool; go by what docker compose ls shows. Cleanup: docker compose -p orders_devcontainer down (replace the project name with the one from the previous output).

Run Testcontainers inside the dev container (reproduce the networking trap)
devcontainer exec --workspace-folder . bash -lc 'cd app && pytest -q tests 2>&1 | tail -2'
devcontainer exec --workspace-folder . bash -lc 'cd app && TESTCONTAINERS_HOST_OVERRIDE=host.docker.internal pytest -q tests 2>&1 | tail -1'
E   psycopg.OperationalError: connection failed: … Connection refused
1 error in 12.4s
3 passed in 7.9s

With docker-outside-of-docker, the postgres started by Testcontainers maps its port on the host, and localhost inside the dev container is not the host. host.docker.internal must be resolvable on Linux (Docker Desktop provides it; with a Linux engine, add extra_hosts: ["host.docker.internal:host-gateway"] to the dev container's service); alternatively, switch to the docker-in-docker feature.

GPU (optional: needs an NVIDIA GPU VM, not run in this environment)
nvidia-smi --query-gpu=name,driver_version --format=csv,noheader
# after adding the package repository per NVIDIA's official install guide:
sudo apt-get install -y nvidia-container-toolkit
nvidia-ctk --version
sudo nvidia-ctk runtime configure --runtime=docker && sudo systemctl restart docker
docker run --rm --gpus all ubuntu nvidia-smi -L
nvidia-ctk cdi list
docker run --rm --device nvidia.com/gpu=all ubuntu nvidia-smi -L
Tesla T4, 5xx.xx
NVIDIA Container Toolkit CLI version 1.20.2
GPU 0: Tesla T4 (UUID: GPU-…)
INFO[0000] Found 3 CDI devices
nvidia.com/gpu=0
nvidia.com/gpu=GPU-…
nvidia.com/gpu=all
GPU 0: Tesla T4 (UUID: GPU-…)

Cost reminder: GPU VMs are billed by the hour and are expensive; stop (deallocate) or delete them right after the lab.

Case 1: "All tests green, crashes in production"

Problem: a team's unit tests used an in-memory SQLite database and all passed; in production, ON CONFLICT … DO NOTHING RETURNING behaved differently than expected on PostgreSQL, breaking the idempotency logic. Fix: switched to Testcontainers starting PostgreSQL with the same major version as production, and the problem surfaced in CI. Onboarding a new colleague went from "two days of environment setup" to "open a Codespace, five minutes". Limitation: CI takes about 10 seconds longer (container startup); a session-scoped fixture reuses one container.

Case 2: inference service won't start after a driver upgrade

Problem: the GPU driver was auto-updated overnight, and in the morning every inference container failed with unresolvable CDI devices. Fix: the CDI spec still pointed at the old driver's library files; after upgrading to Toolkit 1.18+, nvidia-cdi-refresh regenerates it automatically on driver install / upgrade and on reboot; the short-term fix was a manual nvidia-ctk cdi generate. Limitation: the service does not handle driver uninstalls or MIG reconfiguration; those two cases still need a manual refresh.

On Azure

ScenarioSolution
Cloud dev environmentsGitHub Codespaces reads .devcontainer/ directly; Microsoft Dev Box
Integration tests in CIGitHub Actions ubuntu runners come with Docker, so Testcontainers runs as is
GPU inference / trainingNC / ND series VMs; AKS GPU node pools (GPU Operator); Container Apps serverless GPUs (workload profiles, available by region and quota)

GPU SKUs, regional availability and quotas change quickly; check the Azure docs and the quotas in your subscription.

Common errors and fixes

Testcontainers: docker.errors.DockerException: Error while fetching server API version

Cause: the test process can't reach the Docker socket. Fix: on a VM, add the user to the docker group (note this is equivalent to root access); in a dev container, use the docker-outside-of-docker feature.

Running Testcontainers inside the dev container: connection refused / timeout

Cause: with docker-outside-of-docker, the new container's port mappings are on the host, and localhost inside the dev container can't reach them. Fix: set TESTCONTAINERS_HOST_OVERRIDE=host.docker.internal (and make sure it resolves), or switch to the docker-in-docker feature.

could not select device driver "" with capabilities: [[gpu]]

Cause: the NVIDIA Container Toolkit isn't installed, or there is neither a CDI spec nor a run of nvidia-ctk runtime configure. Fix: install the Toolkit, configure the runtime and restart Docker; or make sure a CDI spec exists.

unresolvable CDI devices nvidia.com/gpu=all

Cause: the CDI spec is missing or stale (after a driver upgrade). Fix: sudo systemctl restart nvidia-cdi-refresh.service or sudo nvidia-ctk cdi generate --output=/var/run/cdi/nvidia.yaml; use nvidia-ctk --debug cdi list to see loading errors.

CUDA driver version is insufficient for CUDA runtime version inside the container

Cause: the CUDA runtime in the image is newer than what the host driver supports. Fix: upgrade the host driver, or use an image with an older CUDA version (the top right of nvidia-smi shows the highest CUDA version the driver supports).

devcontainer up reports service "dev" refers to undefined … or missing variables

Cause: compose.yaml depends on .env variables, and there is no .env when the dev container starts. Fix: first cp .env.example .env and fill it in (done in Module 0).

Command-line exercises
1. Confirm that no containers (including Ryuk) are left behind after the Testcontainers tests.
docker ps -a --filter label=org.testcontainers --format '{{.Names}}\t{{.Image}}\t{{.Status}}'
2. List the CDI GPU devices available on the host, and run nvidia-smi with one of them.
nvidia-ctk cdi list
docker run --rm --device nvidia.com/gpu=0 ubuntu nvidia-smi -L
Scenario analysis
The team wants to "run tests in the Dev Container" in CI to guarantee consistency with the developer environment. Is that feasible? What should they watch out for?

Feasible: devcontainer up + devcontainer exec … pytest (or the official devcontainers/ci Action). Watch out: ① Testcontainers inside the dev container needs access to Docker (docker-outside-of-docker) and must handle the host port issue; ② cache the dev container image in CI (push a prebuilt image to a registry), otherwise features are installed every time; ③ postCreateCommand must not rely on interactive input; ④ it is not the same image as production, so you still need a smoke test of the production image at the end (hour 5).

About teaching videos

No verifiable, high-quality video covering current usage of Testcontainers 4.x and Docker CDI could be found. Below are official resources and a storyboard script.

Video storyboard script (about 70 seconds)

Shot 1 · 0–25s
Visual: 20 installation steps pop up on a new colleague's laptop; cut to opening the repo and clicking "Reopen in Container", and five minutes later postgres, redis and rabbitmq are all ready.
Narration: The development environment is written as code and versioned together with the repo.
Shot 2 · 25–45s
Visual: the moment pytest starts, a postgres container appears; when the tests end, it vanishes like a soap bubble.
Narration: Test against a real database, and clean up automatically afterwards.
Shot 3 · 45–70s
Visual: the GPU host as a three-layer cake - driver, Toolkit and CDI spec, CUDA container; after a driver upgrade the middle layer flickers and nvidia-cdi-refresh refreshes it automatically.
Narration: The driver lives on the host, the runtime lives in the image, and the Toolkit and CDI connect the two.
or score ≥ 70% on the "Quiz" tab

Module 8 · Fault Blind Box + Seven-Hour Recap

50:00 – 60:00 · 8 random faults, symptoms only: use the methods and tools from the first seven modules to find the root cause and state the evidence chain; then review the seven-hour knowledge map
10 minBlind box + troubleshooting tree + recap★★★★★
Learning objectives
  • Under time pressure, locate faults via "symptom → layer → evidence → root cause", and tell apart faults that "look alike" (#2 vs #3, #4 vs #7, #1 vs #6).
  • Build the habit of collecting evidence first and fixing second, and write the evidence chain in one sentence: status code / latency → log location → config or resource evidence → root cause.
  • Use the interactive troubleshooting tree to classify every fault in this hour; review the seven-hour knowledge map and know what to learn next.
Prerequisites: Modules 1–7. Importance: ★★★★★

How to play

  1. bash chaos/blindbox.sh start injects a random fault (the answer is stored base64-encoded in chaos/.state; no peeking).
  2. bash chaos/blindbox.sh traffic sends the same mixed traffic; look at status codes and latency and compare with the baseline saved in Module 0.
  3. Investigate with any tool (the "investigation route" below is recommended).
  4. bash chaos/blindbox.sh answer N submits a number (1–8) and shows whether it is correct and how long you took.
  5. bash chaos/blindbox.sh reset restores everything; then draw the next one. reveal shows the answer, list lists the 8 fault names.

The 8 faults (names are public; which one gets injected is random)

#FaultHow it is injectedRelated module
1Connection pool exhaustionpool 2, --threads 8, pool wait 3 sM3 ①
2gunicorn worker timeout--timeout 3M3 ②
3Gateway read timeout 504proxy_read_timeout 2sM3 ②
4Wrong DNS resolutionextra_hosts: postgres → 10.255.255.1M3 ③
5Source port (SNAT) exhaustionip_local_port_range 60000 60007M3 ④
6CPU throttlingcpus: "0.1"M4
7OOM (memory limit)memory: 128MHour 2 · M1 · M4
8Temp directory full/tmp is a 64 KB tmpfsM6 storage

Investigation route (recommended)

  1. RED: which endpoints fail? Which status codes? Is the latency exactly some timeout value? (output of traffic.sh)
  2. Container state: is any container restarting / unhealthy? OOMKilled, exit code?
  3. First error: the earliest error in the api and gateway logs.
  4. Config diff: environment variables and HostConfig (ExtraHosts, Sysctls, NanoCpus, Memory, Tmpfs) compared with the baseline.
  5. Resource evidence: cpu.stat, PSI, df -h /tmp, TIME_WAIT count.
Scoring suggestion3 points for a correct answer within 5 minutes, 2 within 10 minutes, 1 after that; you must also state the evidence (which log line / which value). In pairs, one person operates and the other records the evidence chain.

Seven-hour knowledge map

HourTopicKey skills used in this hour
Hour 1Core fundamentals: images, containers, namespaces / cgroups, networks and volumesA container = a constrained process → nsenter and py-spy work on it directly
Hour 2Production readiness: multi-stage builds, non-root, health checks, resource limits, exit codes137 = OOM; --cpus → cpu.max
Hour 3To the cloud (Azure): ACR, Container Apps, KQLACA ingress 240 s; ContainerAppConsoleLogs queries
Hour 4To the cloud (AWS): ECR, ECS on Fargate, CloudWatchHow the same timeout chain and SNAT problems show up on ALB / NAT gateway
Hour 5Image CI, supply chain and release: cache backends, SBOM, signing, rollbackRelease record → roll back first to mitigate; reproducible builds and signing support each other
Hour 6Application architecture: orders (API, Worker, gateway, migrations, object storage)Connection budget, embedded DNS, async tasks: the "scene" of every fault in this hour
Hour 7Deep troubleshooting, optimization and advanced topicsEvidence collection → find the layer → the three tools → fix → optimization report
Next stepsHour 8 (optional): 50 production issues + 50 interview questions; practice each one with this hour's method. After that, move on to Kubernetes in 8 + 1 Hours (Chinese): kubectl debug, ephemeral containers and node-pressure eviction are the orchestration-platform counterparts of this hour's tools (K8s hour 6 Module 3 (Chinese)); for monitoring and alerting see Prometheus & Grafana (Chinese).

Evidence matrix: status code × latency × location

Symptom Key evidence Conclusion Only dbsleep 500, ≈ 3.0 sPoolTimeout · DB_POOL_SIZE=2 · --threads 8#1 Connection pool exhaustion All slow requests 500, ≈ 3 sWORKER TIMEOUT · was sent SIGKILL#2 gunicorn timeout Slow requests 504, ≈ 2.0 sgateway: upstream timed out; api log 200#3 Gateway read timeout All 502, api Restarting (3)pool initialization incomplete · ExtraHosts#4 Wrong DNS resolution Some POST 500, fastCannot assign requested address · Sysctls#5 Source port exhaustion No errors, all slowercpu.max 10000 · nr_throttled ≈ nr_periods#6 CPU throttling Many 502, Restarting (137)OOMKilled=true · Memory 128M#7 OOM (memory) Only uploads 500Errno 28 · df -h /tmp 64K#8 Temp directory full
Figure 8-1 Group first by "status code + latency + which endpoint", then confirm with one piece of config or resource evidence

Seven-hour roadmap

① BasicsProcess · image ② Prod-readyLimits · health ③ AzureACR · ACA ④ AWSECR · ECS ⑤ Image CISupply · release ⑥ App designorders ⑦ Debug & tuneYou are here → ⑧ optional · Kubernetes
Figure 8-2 The seven-hour Docker main track; hour 8 is optional practice, then on to Kubernetes

Blind box simulator (practice in the browser)

You can practice even without a VM: draw a fault, click the evidence buttons (each new piece of evidence costs 1 minute), then answer. A wrong answer still shows you the answer and its key signature. The evidence is based on this hour's measurements and example output.

Seven-hour flashcards

Click an hour to draw a random "mechanism question"; answer it in your head first, then click "Show answer". The matching verification command appears below.

Pick an hour to start.
$ # the verification command will appear here

Investigation route (copy and use)

bash chaos/blindbox.sh traffic                         # ① which endpoints fail? status codes? latency?
docker compose ps                                      # ② is any container restarting / unhealthy?
docker inspect -f '{{.State.OOMKilled}} {{.State.ExitCode}} {{.RestartCount}}' orders-api-1
docker compose logs api gateway --since 3m | grep -E 'ERROR|CRITICAL|Error|error' | sort | uniq -c | sort -rn | head   # ③ error summary
docker exec orders-api-1 env | grep -E 'DB_POOL|GUNICORN'                                                             # ④ config diff
docker inspect orders-api-1 -f '{{.HostConfig.ExtraHosts}} {{.HostConfig.Sysctls}} {{.HostConfig.NanoCpus}} {{.HostConfig.Memory}} {{.HostConfig.Tmpfs}}'
docker exec orders-api-1 sh -c 'cat /sys/fs/cgroup/cpu.stat | head -3; df -h /tmp | tail -1'                         # ⑤ resource evidence

chaos/blindbox.sh (already included in the orders project)

#!/usr/bin/env bash
# Fault blind box: bash chaos/blindbox.sh start [1-8] | traffic | answer <number> | reveal | reset
set -uo pipefail
cd "$(dirname "$0")/.."
DC=(docker compose -f compose.yaml -f chaos/base.yaml)
STATE=chaos/.state
NAMES=("" "connection pool exhaustion" "gunicorn worker timeout" "gateway read timeout 504" "wrong DNS resolution" "source port (SNAT) exhaustion" "CPU throttling" "OOM (memory limit)" "temp directory full")
case "${1:-}" in
  start)
    n=${2:-$(( RANDOM % 8 + 1 ))}
    sed 's/proxy_read_timeout 30s;/proxy_read_timeout 2s;/' gateway/nginx.conf > chaos/.nginx-f3.conf
    "${DC[@]}" -f chaos/f$n.yaml up -d --quiet-pull >/dev/null 2>&1
    echo "$n" | base64 > $STATE; date +%s >> $STATE
    echo "Blind box ready (${2:+picked #$n}${2:-random}). Run bash chaos/traffic.sh to see the symptoms, then start investigating.";;
  traffic) bash chaos/traffic.sh;;
  answer)
    n=$(head -1 $STATE | base64 -d); t0=$(sed -n 2p $STATE); el=$(( $(date +%s) - t0 ))
    if [ "${2:-}" = "$n" ]; then echo "✓ Correct: #$n ${NAMES[$n]}, took $((el/60)) min $((el%60)) s"; else echo "✗ Wrong, look for more evidence (hint: check the status codes and the first error in the api log)"; fi;;
  reveal) n=$(head -1 $STATE | base64 -d); echo "Answer: #$n ${NAMES[$n]} (injection file chaos/f$n.yaml)"; cat chaos/f$n.yaml;;
  reset) "${DC[@]}" up -d --force-recreate api gateway >/dev/null 2>&1; rm -f $STATE; echo "Normal configuration restored";;
  list) for i in $(seq 8); do echo "#$i ${NAMES[$i]}"; done;;
  *) echo "Usage: $0 start [1-8] | traffic | answer <1-8> | reveal | reset | list";;
esac

Injection files (excerpt)

services:
  api:
    environment:
      DB_POOL_SIZE: "2"
      DB_POOL_TIMEOUT: "3"
      GUNICORN_CMD_ARGS: "--threads 8"
services:
  api:
    sysctls:
      net.ipv4.ip_local_port_range: "60000 60007"
services:
  api:
    tmpfs:
      - /tmp:size=64k

chaos/traffic.sh first sends 12 concurrent 4-second report queries, then 37 mixed requests (stats, orders, 40 ms compute, 4 MB memory, 4-second wait, 600 KB upload), and finally prints the status codes and average latency per endpoint. With the normal configuration everything succeeds (measured: 36×200, 3×201, 10×202).

Round 1: warm-up with a chosen fault
bash chaos/blindbox.sh start 8
bash chaos/blindbox.sh traffic
docker compose logs api --since 2m | grep -m1 -o 'OSError.*'
docker exec orders-api-1 df -h /tmp | tail -1
bash chaos/blindbox.sh answer 8; bash chaos/blindbox.sh reset
== Status code counts ==
     36 200
     10 202
      3 500
…
500 UPLOAD /api/files                                3  0.05s
OSError: [Errno 28] No space left on device
tmpfs   64.0K   4.0K  60.0K   6% /tmp
✓ Correct: #8 temp directory full, took 2 min 13 s

A 600 KB upload exceeds Werkzeug's in-memory threshold and is written to a temp file in /tmp, but /tmp only has 64 KB.

The real blind box: 3 random rounds
for round in 1 2 3; do
  bash chaos/blindbox.sh start
  read -p "Press Enter when you have finished investigating..." _
  read -p "Your answer (1-8): " a; bash chaos/blindbox.sh answer $a
  bash chaos/blindbox.sh reveal | head -1; bash chaos/blindbox.sh reset
done
Write an evidence chain: after each round, record it in one sentence, for example:
#1 connection pool exhaustion: dbsleep 8 × 500, latency 3.01 s (= DB_POOL_TIMEOUT) → api log PoolTimeout → env: DB_POOL_SIZE=2, --threads 8 → threads > pool → fix: pool ≥ threads and check the connection budget

Cleanup: bash chaos/blindbox.sh reset.

Evidence quick reference: what to look at for each fault

#1 Connection pool exhaustion

Only dbsleep fails, the 500s take ≈ 3.0 s; log PoolTimeout: couldn't get a connection after 3.00 sec; env has DB_POOL_SIZE=2 and --threads 8.

#2 gunicorn worker timeout

Every request taking ≥ 3 s returns 500; log [CRITICAL] WORKER TIMEOUT, was sent SIGKILL; env has GUNICORN_CMD_ARGS=--timeout 3.

#3 Gateway read timeout 504

Status 504, latency ≈ 2.0 s; gateway log upstream timed out … while reading response header; the api log shows the request actually succeeded.

#4 Wrong DNS resolution

api is in a restart loop, gateway returns 502; log pool initialization incomplete; ExtraHosts in docker inspect is postgres:10.255.255.1; getent hosts postgres and dig give different results.

#5 Source port exhaustion

Some POST /api/orders return 500 (publishing the message fails), other endpoints are fine; log Cannot assign requested address; Sysctls has ip_local_port_range 60000 60007; lots of TIME_WAIT.

#6 CPU throttling

No errors, but every request is slow, the cpu endpoint especially; cpu.max is 10000 100000; nr_throttled is close to nr_periods; PSI some is high.

#7 OOM (memory limit)

api keeps restarting, gateway returns 502; OOMKilled=true, exit code 137; docker events shows oom; Memory limit 128 MB (the 3 gunicorn processes have a baseline of about 130–180 MB RSS).

#8 Temp directory full

Only uploads fail; OSError: [Errno 28] No space left on device; df -h /tmp shows a 64 KB tmpfs.

The structure of a real incident postmortem

The blind box trains the same skill a real postmortem needs. A blameless postmortem contains at least: impact (time, scope, user-visible symptoms), timeline (detection, evidence collection, mitigation, fix), evidence chain (command output and logs), root cause and trigger, why it wasn't caught earlier (alerts, tests, timeout hierarchy), and action items (with owners and dates). Focus on systems and processes, not on blaming individuals.

Interactive troubleshooting tree: every fault in this hour

Common problems with the blind box script itself

head: cannot open 'chaos/.state' for reading: No such file or directory

Cause: you haven't run start yet, or you already ran reset. Fix: run bash chaos/blindbox.sh start first.

Symptoms persist after reset

Cause: you manually injected into other services with dc -f chaos/fN.yaml, or changed an override such as /tmp/tune.yaml. Fix: dc up -d --force-recreate rebuilds every service; docker compose config confirms the final configuration.

No 504 after injecting #3

Cause: gateway/nginx.conf has been modified, so sed didn't match proxy_read_timeout 30s;. Fix: grep proxy_read_timeout chaos/.nginx-f3.conf to check the generated result.

Command-line exercises
1. In one command, print the api container's OOM flag, exit code, restart count, CPU and memory limits, ExtraHosts, Sysctls and Tmpfs.
docker inspect orders-api-1 -f 'oom={{.State.OOMKilled}} exit={{.State.ExitCode}} restarts={{.RestartCount}} cpus={{.HostConfig.NanoCpus}} mem={{.HostConfig.Memory}} hosts={{.HostConfig.ExtraHosts}} sysctls={{.HostConfig.Sysctls}} tmpfs={{.HostConfig.Tmpfs}}'
2. Diff the current effective Compose config of api against the baseline (without the fault file layered on).
diff <(docker compose -f compose.yaml -f chaos/base.yaml config api) \
     <(docker compose -f compose.yaml -f chaos/base.yaml -f chaos/f5.yaml config api)
Scenario analysis
Two faults both look like "gateway returns lots of 502 and api keeps restarting". Which two pieces of evidence tell #4 and #7 apart within 1 minute?

① The exit code from docker compose ps / docker inspect: #4 is 3 (the app exits because startup failed), #7 is 137 with OOMKilled=true; ② the first error in the log: #4 is pool initialization incomplete (cannot reach the database), #7 is Worker … was sent SIGKILL! Perhaps out of memory?. Then confirm the injection point with HostConfig.ExtraHosts or HostConfig.Memory.

About the teaching video

This module is hands-on practice and has no matching video; you can rewatch the verified talks in Modules 1–2. Further reading:

Video storyboard (about 75 seconds)

Shot 1 · 0–20s
Visual: a gift box drops onto the orders system, the lid opens and a question mark pops out; a timer starts ticking.
Narration: The fault is random, the symptoms are public, and all you have is evidence.
Shot 2 · 20–55s
Visual: evidence cards flip over one by one: status code counts, container state, first error, config diff, resource evidence; the third card lights up and a line of reasoning connects to the answer "#1 connection pool exhaustion".
Narration: Collect evidence along the route; most faults are pinned down by the third card.
Shot 3 · 55–75s
Visual: badges for the seven hours line up in a row and the last one lights up; a Kubernetes helm wheel appears in the distance.
Narration: Seven hours, from a single docker run to troubleshooting production faults. Next stop: Kubernetes.
or score ≥ 70% on the "Quiz" tab

Command Cheat Sheet

Evidence collection, getting into containers, the three tools, connections and timeouts, performance, builds, networking, developer experience and GPUs

Evidence collection (Module 1)

docker inspect -f '{{.State.OOMKilled}} {{.State.ExitCode}} {{.RestartCount}}' COOM, exit code, restart count
docker events --since 30m --until "$(date +%s)" --filter container=Cdie / oom / health events (returns immediately)
docker logs --timestamps --since 10m C 2>&1 | grep -m1 -E 'Error|Traceback'First error
docker inspect C -f '{{json .HostConfig}}' | jq '{NanoCpus,Memory,ExtraHosts,Sysctls,Tmpfs}'Limits and overrides
sudo bash ops/evidence.sh COne-command evidence bundle (this hour's script)

Getting into containers (Module 2)

PID=$(docker inspect -f '{{.State.Pid}}' C)Host PID
sudo nsenter -t $PID -n ss -tanpConnections in the container's network
docker run --rm -it --network container:C nicolaka/netshoot:v0.16Toolbox sharing the network
docker run --rm -it --pid container:C --cap-add SYS_PTRACE nicolaka/netshoot:v0.16Shared PID namespace
docker debug C / docker debug --host ssh://user@vm CDocker Desktop debug shell

The three tools (Module 2)

sudo nsenter -t $PID -n tcpdump -i eth0 -nn -c 100 port 5432Packet capture
sudo timeout 5 strace -f -tt -T -p $P -e trace=network,pollSystem calls (time-limited)
sudo timeout 5 strace -c -f -p $PSystem call summary
sudo py-spy dump --pid $PID -sPython stacks (including subprocesses)
sudo py-spy top --pid $PID -sLive hot spots
sudo py-spy record -o flame.svg --pid $PID -s -d 30Flame graph

Connections, timeouts and DNS (Module 3)

curl -sk -o /dev/null -w '%{http_code} %{time_total}s\n' URLStatus code + duration
getent hosts NAMEThe app's resolution path (includes /etc/hosts)
dig +short NAME / dig @168.63.129.16 NAMEDNS only / query Azure DNS directly
ss -tan state time-wait | wc -lTIME_WAIT count
cat /proc/sys/net/ipv4/ip_local_port_rangeSource port range

Performance (Module 4)

cat /sys/fs/cgroup/cpu.max /sys/fs/cgroup/cpu.statQuota and throttling
cat /sys/fs/cgroup/{cpu,memory,io}.pressureContainer PSI
docker run --rm -i --network orders_default grafana/k6:2.4.0 run - < perf/load.jsLoad test
docker stats --no-streamPoint-in-time resource usage
GUNICORN_CMD_ARGS="--threads 4 --timeout 25"Extra gunicorn arguments
Concurrency = throughput × average latencyLittle's law

Builds (Module 5)

docker buildx create --driver docker-container --driver-opt image=moby/buildkit:v0.35.0 --use --bootstrapStandalone builder with a pinned version
docker buildx create --driver remote --driver-opt cacert=…,cert=…,key=…,servername=… tcp://host:1234Remote buildkitd (mTLS)
docker buildx history ls / history inspect REFBuild records
export SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)Reproducible timestamp
--output type=image,…,rewrite-timestamp=trueRewrite file times in layers
docker buildx bake -f docker-bake.hcl --printInspect the matrix

Networking and storage (Module 6)

docker network create --ipv6 v6netDual-stack network
docker network create -d macvlan|ipvlan -o parent=eth0 --gateway … …Layer 2 network drivers (explicit gateway since 29)
"firewall-backend": "nftables"daemon.json (experimental in Engine 29)
-o com.docker.network.driver.mtu=1400Network MTU
--tmpfs /tmp:size=64mtmpfs with a size limit

Developer experience / GPU (Module 7)

devcontainer up --workspace-folder .Start the dev container
pytest -q (Testcontainers)Integration tests against real dependencies
TESTCONTAINERS_HOST_OVERRIDE=host.docker.internalRunning inside a dev container
sudo nvidia-ctk runtime configure --runtime=dockerConfigure the GPU runtime
docker run --gpus all … / --device nvidia.com/gpu=allRequest GPUs (classic / CDI)
nvidia-ctk cdi listCDI devices

Timeout hierarchy (inside out)

statement_timeoutPool waitgunicorn --timeoutnginx proxy_read_timeoutACA ingress
5 s3–5 s25 s30 s240 s (fixed)

Blind box quick reference (Module 8)

#Status code / durationOne confirming piece of evidence
1dbsleep 500 · ≈ 3.0 sPoolTimeout · DB_POOL_SIZE=2
2Slow requests 500 · ≈ 3 sWORKER TIMEOUT
3Slow requests 504 · ≈ 2.0 sgateway upstream timed out
4All 502 · restarts (3)ExtraHosts postgres:10.255.255.1
5Some POSTs 500 · fastErrno 99 · ip_local_port_range
6All 200 but slowcpu.max 10000 · nr_throttled
7Many 502 · restarts (137)OOMKilled=true
8Only uploads 500Errno 28 · /tmp 64K

Capstone Lab: Load Test and Optimization Report + Final Quiz

About 45 minutes · produces a performance / reliability report you can hand to your team
After class ≈ 45 minCovers all modules
Tasks
  • Establish a performance baseline for the orders api, find the bottleneck, and make at least two rounds of data-backed adjustments (Module 4).
  • Fix a real latent bug in the hour 6 code: queueing.publish() opens a new connection for every message (the root cause of blind box #5, Module 3).
  • Adjust the timeout hierarchy to the values recommended in this hour, and use blind boxes #2 / #3 to verify that the status codes become predictable (Module 3).
  • Attach to the report the evidence script output (Module 1), key call stacks or system calls (Module 2), and a cost impact estimate (Module 4).
Baseline
bash chaos/blindbox.sh reset
docker run --rm -i --network orders_default -e BASE=http://api:8000 grafana/k6:2.4.0 run --summary-export=/dev/stdout --quiet - < perf/load.js 2>/dev/null \
  | jq '{p95: .metrics.http_req_duration["p(95)"], p99: .metrics.http_req_duration["p(99)"], fail: .metrics.http_req_failed.value, rps: .metrics.http_reqs.rate}' | tee baseline.json
docker exec orders-api-1 sh -c 'grep -E "nr_periods|nr_throttled" /sys/fs/cgroup/cpu.stat'

--summary-export writes a JSON summary (field names depend on the k6 version you use); you can also just read the terminal summary and record it by hand.

Fix connection reuse (reference implementation)
import threading
_local = threading.local()

def _publisher_channel():
    """Reuse one long-lived connection and channel per thread; rebuild automatically if disconnected."""
    ch = getattr(_local, "ch", None)
    if ch is None or ch.is_closed or ch.connection.is_closed:
        _local.conn, _local.ch = _rabbit_channel()
    return _local.ch

# In publish():
#   ch = _publisher_channel()
#   ch.basic_publish("", config.QUEUE_NAME, body, pika.BasicProperties(delivery_mode=2, content_type="application/json"))
#   On failure: set _local.ch = None and retry once

pika's BlockingConnection is not thread-safe, so it is stored per thread. Long-lived connections also need heartbeats (pika negotiates them with the server by default); after an idle disconnect, the connection is rebuilt on the next publish. After the change, rerun blind box #5: every POST should return 202, and ss -tan state time-wait should stop growing.

Timeout hierarchy
services:
  api:
    environment:
      DB_POOL_TIMEOUT: "5"
      GUNICORN_CMD_ARGS: "--timeout 25 --graceful-timeout 20"

Note: this hour's dc alias passes -f explicitly, and when files are specified explicitly Compose does not load compose.override.yaml automatically. Use dc -f compose.override.yaml up -d api, or add it to the alias.

Report template (copy into your document and fill in)
RoundChangeP95P99Error rateThroughput (req/s)nr_throttled / nr_periodsMemoryConclusion
0Baseline: cpus 0.5, -w 2, pool 5
1
2

The report should also include: evidence of the bottleneck (command output), the connection budget calculation (hour 6), the cost impact (change in vCPU-seconds / GiB-seconds), and risks and how to roll back.

Cleanup
bash chaos/blindbox.sh reset
docker compose --profile jobs down            # add -v to delete data
docker buildx rm repro bvm 2>/dev/null; docker network prune -f; docker image prune -f
rm -rf evidence-* baseline.json
Discussion questions
1. During the report review someone asks: "Why not just raise the CPU limit from 0.5 to 2?" How do you answer?

Look at the evidence first: if nr_throttled/nr_periods is low and PSI cpu is low, the bottleneck is not the CPU, and adding cores only adds cost. If throttling is heavy, you can either add cores or reduce the number of processes computing at the same time; the choice depends on cost (vCPU-seconds) and the connection budget (more processes mean more connections). Change one thing at a time and compare with the same load test script.

2. After fixing publish(), will blind box #5 still reproduce?

Not in the same form: each thread holds only one long-lived connection, TIME_WAIT stops growing, and 8 ports are enough. But if threads × replicas exceeds the available ports, or long-lived connections are cut by an idle timeout on a middlebox and rebuilt frequently, the problem comes back in another form. That is why you also need heartbeats and sensible idle recycling.

Final quiz (12 questions covering all modules)

The Docker main track is completeSeven 1-hour hours: fundamentals → production readiness → cloud (Azure) → cloud (AWS) → image CI and supply chain → application architecture → deep troubleshooting and optimization. Hour 8 (optional) offers 50 production problems and 50 interview questions; after that, move on to Kubernetes in 8 + 1 Hours (Chinese).

Sources and Version Notes

The basis for verifying this hour's technical facts (verified: 2026-11-17)
TopicVerified findingSources (accessed 2026-11-17)
Docker Engine / buildx / BuildKitEngine v29.10.0 (2026-11-16, bundles BuildKit v0.35.0); buildx v0.39.0 (2026-11-11); BuildKit v0.35.0 (2026-11-11); Compose v5.8.0 (2026-11-17)moby/moby releases · docker/buildx · moby/buildkit · Engine 29 release notes
nftables backendExperimental since 29.0.0 (firewall-backend); Docker owns the docker-bridges table; there is no DOCKER-USER; host IP forwarding is required; the docs say it cannot be enabled in Swarm mode, while the 29.10.0 release notes say nftables engines "can now join a Swarm (experimental)"; since 29.0.0 docker info reports the firewall backendDocker with nftables · Engine 29 release notes
macvlan / ipvlanSince 29.0.0, macvlan and ipvlan-l2 networks do not configure a default gateway unless --gateway is specified explicitlyEngine 29 release notes · macvlan driver
CDI and GPUsCDI is enabled by default since Engine 28.3.0; since 29.2.0, --gpus requests for NVIDIA devices are handled via CDI where possible; since 29.3.0, --gpus for AMD GPUs uses CDI; latest NVIDIA Container Toolkit v1.20.2 (2026-11-17); since 1.18.0, nvidia-cdi-refresh generates /var/run/cdi/nvidia.yaml automatically (it does not handle driver uninstalls or MIG reconfiguration)Engine 28 release notes · NVIDIA/nvidia-container-toolkit · NVIDIA CDI support
docker debugA Docker Desktop CLI command; supports containers / images without a shell, install of Nix packages, and --host to connect to a remote engine; free for all users since Desktop 4.49.0 (2025-10-23); latest Desktop 4.99.0 (2026-11-09)docker debug reference · Docker Desktop release notes
Builds at scaleThe remote driver's cacert/cert/key/servername options and buildkitd --tlscacert/--tlscert/--tlskey; docker buildx history subcommands ls / inspect / logs / open / rm / trace / export / import; SOURCE_DATE_EPOCH (BuildKit ≥ 0.11; buildx ≥ 0.10 passes the environment variable automatically; special value context); rewrite-timestamp (BuildKit ≥ 0.13); compatibility-version (currently 30)Remote driver · buildx history · BuildKit build-repro
Diagnostic toolspy-spy 0.4.3 (2026-11-02, latest); netshoot v0.16 (2026-07-01, latest tag; the README recommends pinning by digest for production debugging); strace 6.8, tcpdump 4.99.4, util-linux nsenter 2.39.3 (versions measured in the generation environment)benfred/py-spy · nicolaka/netshoot
k6v2.4.0 (2026-11-12) is the latest 2.x; 1.x is still maintained (v1.8.3); the Docker Hub tag grafana/k6:2.4.0 existsgrafana/k6 releases
Testcontainers / Dev Containerstestcontainers-python 4.15.0 (2026-07-24, latest on PyPI); new import path testcontainers.community.postgres; @devcontainers/cli 0.90.0 (2026-10-28, latest on npm)testcontainers-python · @devcontainers/cli
AzureContainer Apps HTTP ingress request timeout is 240 seconds; NAT Gateway provides 64,512 SNAT ports per public IP; private endpoints depend on private DNS zones linked to the VNetACA ingress · NAT Gateway · Private endpoint DNS
Kernel and methodologycgroup v2 cpu.max / cpu.stat, PSI; the USE / RED methodscgroup v2 · PSI · USE Method

Testing notes

  • Measured in the generation environment (at the process level, using the same gunicorn 23 / psycopg 3.2 / nginx configuration as the containers): connection pool exhaustion (8 × 500, 3.01 s), gunicorn timeout (500 + WORKER TIMEOUT), nginx 504 (3.0 s), statement_timeout (5.0 s), source port exhaustion (with 50 ports, the 51st connection gets EADDRNOTAVAIL), CPU quota throttling (cgroup v1: 0.5 s of CPU work took 1.96 s, 20/22 periods throttled), tmpfs full (ENOSPC), py-spy dump and strace output, the traffic.sh baseline (all successful), Bake --print (buildx 0.38), the Testcontainers test logic (against a local PostgreSQL: 3 passed, with a deprecation warning for the old import path), and config -q for every compose override file.
  • Not run: any step that needs to pull images: the full Compose run, containerized reproduction of the DNS / OOM / CPU faults, k6, netshoot, the evidence script, the tcpdump lab, docker debug, macvlan / ipvlan / IPv6 / nftables / MTU, the reproducible build digest comparison, build records, the remote builder, starting the Dev Container, and GPUs. These were written from the official documentation, and their "Expected output" blocks are examples.
  • The generation environment is a cgroup v1 + v2 hybrid; the course is written using the cgroup v2 file names of Ubuntu 24.04.

Notes on video verification

The titles and channels of the following videos were verified via the YouTube oEmbed endpoint (2026-11-17): Liz Rice "Containers From Scratch • GOTO 2018" (8fi7uSYlOdc); Docker "Cgroups, namespaces, and beyond: what are containers made from?" (sK5i-N34im8); Brendan Gregg "Linux Performance Tools" part 1 (FJW8nGV4jxY) and part 2 (zrr2nUln9Kk); CNCF "Container Networking From Scratch - Kristen Jacobs" (6v_BDHIgOY8); NetworkChuck "Docker networking is CRAZY!!" (bKFMS5C4CG0); Christian Lempa "Docker Networking Tutorial, ALL Network Types explained!" (5grbXvV_DSk). A multi-stage build video from the old version (yyJrZgoNal0) is no longer reachable via oEmbed and has been removed. For Modules 5, 7 and 8 no verifiable video covering current usage was found, so storyboard scripts are provided.

Notes on the audio explanations

The "Audio" tab uses the browser's Web Speech API (speechSynthesis, en-US) to read the scripts aloud in real time; quality depends on the voices installed on your system. No MP3 is embedded in this courseware; if you need offline audio, feed the scripts to a TTS tool.

Known limitations

  • The display names of the firewall backend and CDI fields in docker info, the columns and fields of docker buildx history ls / inspect, and the output format of nvidia-ctk --version were written from the documentation; your actual version takes precedence.
  • nftables backend and Swarm: the official nftables docs page and the 29.10.0 release notes disagree (the former says it cannot be enabled in Swarm mode, the latter says it can join a Swarm, experimentally); this hour lists both.
  • Container Apps metric names, serverless GPU regions and quotas, and ACA unit prices are as shown in the portal and on the pricing page; the cost calculator only computes resource usage.
  • Timings, steps and logs in the animations are illustrative and meant to explain the mechanisms; the key numbers (3.01 s, 5.0 s, ENOSPC, EADDRNOTAVAIL) are measured.