โšก
Zero to Platform Architect2026
Phase 0: Primitives & Linux

Lesson 4: Docker & Containerization Primitives

๐Ÿง  The Concept (Explain Like Iโ€™m 5)

In the 1950s, cargo ships took days to load because cargo was loose: barrels of wine, sacks of grain, crates of tools, and livestock were crammed haphazardly into the hull. If a barrel broke, everything around it was ruined. If a crane in New York was sized differently than a crane in London, unloading took weeks.

Then came the Standard Intermodal Shipping Container:

  • It doesnโ€™t matter what is insideโ€”whether it carries fine wine, expensive cars, or dry grain.
  • The container has standardized dimensions, corner castings, and twist-locks that fit onto every crane, semi-truck, freight train, and cargo ship in the world.

Docker is the shipping container for software:

  • It packages your compiled application code, runtime engine, system libraries, configuration files, and dependencies into a single immutable artifact (The Image).
  • If that container runs on an engineerโ€™s MacBook, it is mathematically guaranteed to run identically on an AWS EC2 instance, an Azure VM, a Google Cloud Run service, or a Kubernetes cluster.

๐Ÿข The Enterprise Context (Why Platform Architects Care)

  1. Environmental Parity & โ€œIt Works on My Machineโ€: Before containers, configuration drift between developer laptops and production servers caused 40% of deployment failures. Containers eliminate environment drift by bundling the user-space filesystem with the application.
  2. Resource Density & Boot Speed: Traditional Virtual Machines require an entire guest operating system with a separate virtualized kernel (consuming 1โ€“4 GB of RAM per VM and taking 60 seconds to boot). Containers share the host Linux kernel, booting in under 200 milliseconds and consuming only the memory required by the active application process.
  3. The OCI Standard (Open Container Initiative): Docker popularized containers, but enterprise infrastructure relies on OCI standards (image-spec and runtime-spec). Today, Kubernetes does not even use Docker directly; it communicates through the Container Runtime Interface (CRI) to containerd and executes processes using runc.

๐Ÿ—บ๏ธ Visual Architecture: VM vs. Container & The OCI Runtime Stack

flowchart TD
    subgraph VMArch ["Traditional Virtual Machine (Hypervisor-Based)"]
        direction TB
        VM_App1["App A (Java)"] --> VM_Libs1["Bins & Libs"]
        VM_Libs1 --> GuestOS1["Guest OS (Ubuntu ~2GB RAM)"]
        
        VM_App2["App B (Node)"] --> VM_Libs2["Bins & Libs"]
        GuestOS2["Guest OS (RHEL ~2GB RAM)"]
        VM_Libs2 --> GuestOS2
        
        GuestOS1 --> Hypervisor["Hypervisor (Type 1/2: ESXi / KVM / Nitro)"]
        GuestOS2 --> Hypervisor
        Hypervisor --> HostHW1["Physical Bare-Metal Hardware"]
    end

    subgraph OCIStack ["Modern Container Architecture (Shared Host Kernel)"]
        direction TB
        DockerCLI["Docker CLI / kubectl"] --> Daemon["dockerd / containerd"]
        Daemon --> Shim["containerd-shim"]
        Shim --> Runc["runc (OCI Reference Runtime)"]
        Runc -->|"Configures Namespaces & cgroups"| Kernel["Shared Host Linux Kernel Core"]
        
        subgraph IsolatedContainers ["Isolated Process Namespaces"]
            C1["Container A (App + Libs)"]
            C2["Container B (App + Libs)"]
        end
        
        Kernel --> C1
        Kernel --> C2
        Kernel --> HostHW2["Physical Bare-Metal Hardware"]
    end

๐Ÿ”ฌ Under the Hood: Container Engine Internals & OverlayFS

When a container runs, it does not copy 500MB of operating system files. It uses OverlayFS, a union mount filesystem that combines multiple directory trees into a single unified view.

flowchart BT
    subgraph HostDisk ["Host Storage (/var/lib/docker/overlay2)"]
        L1["<b>Layer 1 (lowerdir)</b>: debian:bookworm-slim (Read-Only)"]
        L2["<b>Layer 2 (lowerdir)</b>: install python3 runtime (Read-Only)"]
        L3["<b>Layer 3 (lowerdir)</b>: install pip dependencies (Read-Only)"]
        L4["<b>Layer 4 (lowerdir)</b>: copy application code (Read-Only)"]
        Upper["<b>Container Layer (upperdir)</b>: Ephemeral Read/Write Layer (Writable)"]
    end

    subgraph ContainerMount ["Container View (/mnt/merged)"]
        Merged["<b>Unified Merged View</b><br/>App sees standard root filesystem: /bin, /etc, /app, /var"]
    end

    L1 --> L2
    L2 --> L3
    L3 --> L4
    L4 --> Upper
    Upper --> Merged
    L1 -.-> Merged
    L2 -.-> Merged
    L3 -.-> Merged
    L4 -.-> Merged

Copy-on-Write (CoW) Mechanics

  1. Reading a file: If the container reads /etc/nginx/nginx.conf, the kernel searches from the top down. It finds the file in lowerdir and reads it directly from the immutable base image.
  2. Modifying a file: The moment a container modifies a file that exists in lowerdir, OverlayFS performs a copy-up operation: it duplicates the entire file into the writable upperdir and applies modifications there. The lower layer remains 100% untouched.
  3. Deleting a file: If a container deletes a file located in lowerdir, OverlayFS creates a whiteout device (a character device with major/minor numbers 0/0) inside upperdir. The merged view hides the file from the container.

๐Ÿ—๏ธ Dockerfile Layer Caching & Multi-Stage Build Optimization

Every instruction in a Dockerfile (FROM, RUN, COPY) creates a new layer that Docker caches using a cryptographic hash of its contents and its parent layer.

The Layer Cache-Busting Rule

  • If a layer changes, all subsequent layers are invalidated and must be re-executed from scratch!
  • Anti-Pattern: Copying all application files before installing dependencies:
    # BAD: Any code edit busts cache for slow dependency install!
    COPY . /app
    RUN npm install
  • Best Practice: Copy dependency descriptors first, install libraries, and copy source code last:
    # GOOD: npm install is cached unless package.json changes!
    COPY package.json package-lock.json ./
    RUN npm ci
    COPY . ./

Enterprise Multi-Stage Build Pattern

Compilers, SDKs, and build tools (e.g., Go compiler, GCC, npm build devDependencies) should never exist in production container images. They inflate image sizes and introduce thousands of Common Vulnerabilities and Exposures (CVEs).

# ==============================================================================
# Stage 1: Build & Compile (Heavyweight Build Environment)
# ==============================================================================
FROM golang:1.22-alpine AS builder

# Install security certificates and git for module fetching
RUN apk add --no-cache ca-certificates git

WORKDIR /build

# Cache dependency layer separately from code
COPY go.mod go.sum ./
RUN go mod download

# Copy source code and compile statically linked binary
COPY . .
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
    -ldflags="-w -s -X main.version=1.4.2" \
    -o /build/api-server ./cmd/server

# ==============================================================================
# Stage 2: Minimal Distroless Production Runtime
# ==============================================================================
# Google Container Tools Distroless contains ONLY the application and runtime dependencies.
# Zero shell (/bin/sh), zero package manager (apk/apt), zero compilers!
FROM gcr.io/distroless/static-debian12:nonroot

WORKDIR /app

# Copy compiled static binary from builder stage
COPY --from=builder /build/api-server /app/api-server

# Enforce least-privilege non-root execution (UID 65532)
USER nonroot:nonroot

# Document intended listening port
EXPOSE 8080

# Execute statically compiled binary
ENTRYPOINT ["/app/api-server"]

Result: Image size plummets from 850MB down to 12MB, with zero shell binaries for attackers to exploit during remote code execution (RCE) attacks!


๐Ÿ”Œ Container Networking: Bridge, Host & iptables NAT

A container runs inside its own isolated Linux Network Namespace (netns). To route external traffic into a container, Docker manipulates the hostโ€™s Linux kernel network stack:

flowchart LR
    Client["Client Request<br/>http://192.168.1.100:8080"] --> NIC["Host Physical Interface (eth0)"]
    
    subgraph HostKernel ["Host Linux Kernel Network Stack"]
        NIC --> IPTables["iptables NAT Table<br/>(PREROUTING: DNAT to 172.17.0.2:80)"]
        IPTables --> DockerBridge["docker0 Linux Bridge<br/>(Default Gateway: 172.17.0.1)"]
        DockerBridge --> VethHost["veth-host interface"]
    end
    
    subgraph ContNetns ["Container Network Namespace (netns)"]
        VethHost --> VethGuest["eth0 interface<br/>(IP: 172.17.0.2)"]
        VethGuest --> AppPort["App Listening on Port 80"]
    end

Docker Network Modes Comparison

  1. bridge (Default): The container gets a private virtual IP (e.g., 172.17.0.2) on the internal docker0 software bridge. Ports are exposed to the external world via iptables Destination Network Address Translation (DNAT): docker run -p 8080:80.
  2. host: Removes network isolation entirely. The container shares the hostโ€™s network namespace directly (--net=host). Port mapping is not needed; binding to port 80 binds directly to host port 80. Offers maximum throughput with zero NAT overhead.
  3. none: Disables all networking. The container only possesses the loopback interface (127.0.0.1). Used for offline batch cryptographic or data transformation workloads.
  4. container:<name>: Joins another existing containerโ€™s network namespace directly. This is the exact underlying primitive Kubernetes uses to implement multi-container Pods (sharing localhost between an application container and a sidecar proxy).

๐Ÿ›‘ Signals & Process Management: Shell Form vs. Exec Form

A frequent cause of production deployment outages is containers failing to stop gracefully during deployments. This almost always boils down to how ENTRYPOINT and CMD are declared:

The Shell Form (The Silent Killer)

# Anti-Pattern: Shell Form
ENTRYPOINT python app.py
  • What Docker executes: /bin/sh -c "python app.py"
  • Process hierarchy: /bin/sh runs as PID 1, and python app.py runs as PID 2.
  • The Failure: When Docker or Kubernetes stops the container, it sends SIGTERM to PID 1 (/bin/sh). Most shell implementations do not forward signals to child processes!
  • The Outage: The Python application never receives SIGTERM. It continues accepting traffic until the 10-second (or 30-second in K8s) graceful termination timer expires, at which point the kernel abruptly executes kill -9 (SIGKILL), dropping active user transactions and corrupting state.

The Exec Form (The Production Standard)

# Production Standard: Exec Form (JSON Array Syntax)
ENTRYPOINT ["python", "app.py"]
  • What Docker executes: python app.py directly without a wrapper shell.
  • Process hierarchy: python runs as PID 1 directly.
  • The Result: The application intercepts SIGTERM immediately, finishes active database transactions, closes open TCP sockets cleanly, and exits with code 0.

๐Ÿ› ๏ธ Essential Docker CLI Command Playbook

# 1. Build an image with multi-platform support using Buildx
docker buildx build --platform linux/amd64,linux/arm64 -t registry.corp.internal/apps/payment:v2.1.0 .

# 2. Run container with strict resource limits and read-only filesystem
docker run -d \
  --name payment-api \
  -p 8080:8080 \
  --memory="512m" \
  --cpus="1.5" \
  --read-only \
  --tmpfs /tmp:rw,noexec,nosuid,size=64m \
  -v app_logs:/var/log/app \
  --cap-drop=ALL \
  --cap-add=NET_BIND_SERVICE \
  registry.corp.internal/apps/payment:v2.1.0

# 3. Live observability: Monitor real-time CPU, RAM, Network, and Block I/O usage
docker stats --no-stream

# 4. Deep Inspection: View network configuration, IP address, and mounts
docker inspect payment-api | grep -E "IPAddress|OomKilled"

# 5. File System Diff: Inspect all files modified in the container's writable layer
docker diff payment-api
# Output:
# C /var/log         (C = Changed)
# A /var/log/app.log (A = Added)

# 6. Reclaim disk space: Remove dangling images, build caches, and unused volumes
docker system prune -a --volumes -f

โš ๏ธ Real-World Failure Modes & Troubleshooting Playbook

Scenario 1: โ€œNo space left on deviceโ€ in /var/lib/docker/overlay2

  • Symptom: CI/CD runners or container host nodes fail to pull new images with no space left on device, despite df -h showing root partition usage under 60%.
  • Root Cause: BuildKit cache accumulation and thousands of dangling intermediate image layers from continuous CI builds consuming 100% of the /var/lib/docker volume or exhausting disk inodes (df -i).
  • Resolution:
    # Check disk space and inode consumption
    df -h /var/lib/docker
    df -i /var/lib/docker
    
    # Clean unreferenced layers and BuildKit builder cache
    docker builder prune -a -f
    docker image prune -a -f

Scenario 2: Alpine Linux DNS Failures Under Heavy Load

  • Symptom: High-throughput microservices built on alpine:latest experience intermittent 5-second connection timeouts when resolving internal domain names.
  • Root Cause: Alpine Linux uses musl libc instead of GNU glibc. Musl libc sends standard A and AAAA (IPv6) DNS queries concurrently over the same UDP socket without retry queuing. Under high concurrency, stateful firewalls and NAT connection tracking (conntrack) drop the overlapping UDP packet, resulting in a 5-second DNS fallback delay.
  • Resolution: In high-throughput enterprise architectures, prefer Debian-slim (debian:bookworm-slim) or Distroless base images which utilize glibc, or deploy a local DNS caching agent (e.g. NodeLocal DNSCache).

๐Ÿ“ Staff Architect & SRE Interview Scenarios

โ“ Question 1: Container Escape via the Docker Socket Mount

Question: Why do platform security policies strictly forbid mounting /var/run/docker.sock into an untrusted container (e.g., -v /var/run/docker.sock:/var/run/docker.sock), and how does this represent an immediate root escape?

Answer: The Docker daemon (dockerd) runs with root privileges on the host system. The Docker socket /var/run/docker.sock is the Unix domain socket through which the Docker API accepts management commands. If an unprivileged container has read/write access to this socket, an attacker can simply send an API call to the daemon to spawn a new privileged container with the hostโ€™s root filesystem mounted to /host:

docker run -v /:/host --privileged -it alpine chroot /host

This grants the attacker unrestricted root access to the entire host operating system, bypassing all container namespaces and cgroup boundaries.

โ“ Question 2: Memory Limits vs Swap Accounting

Question: What happens when you configure --memory 512m on a container, but do not set --memory-swap? How can this lead to node-level degradation?

Answer: If --memory-swap is not explicitly configured, Docker defaults to allowing the container to consume swap space equal to twice the memory limit (i.e., 512MB RAM + 512MB Swap = 1024MB total). When the container exceeds 512MB of RAM, the Linux kernel begins swapping memory pages to the host disk. Disk I/O latency is orders of magnitude slower than RAM, causing the application to stall and driving up node disk queue depth. This induces severe I/O thrashing, degrading every other workload on the shared host. In enterprise production, set --memory-swap equal to --memory (e.g., --memory 512m --memory-swap 512m) to completely disable swap allocation and force deterministic OOM termination.