Containers & Kubernetes: Fundamentals, Scaling, Self-Healing, Services & Ingress
"Because all action is based on observation rather than a state diagram, reconciliation loops are robust to failures and perturbations: when a controller fails or restarts it simply picks up where it left off." — Brendan Burns, Brian Grant, David Oppenheimer, Eric Brewer and John Wilkes, Borg, Omega, and Kubernetes, ACM Queue, January–February 2016
Summary: A container is an ordinary Linux process that the kernel isolates with namespaces and limits with cgroups, started from an image (a stack of read-only layers described by the OCI image spec). Kubernetes is a control plane that stores the desired state of many such processes and runs reconciliation loops that keep pulling the real cluster towards it: it schedules pods onto nodes, restarts them when probes fail, replaces them when nodes die, rolls out new versions within maxSurge/maxUnavailable, scales them with the HPA, and routes traffic to the ready ones through Services and Ingress or Gateway API. Focus: Images, layers, OCI, namespaces, cgroups and the Dockerfile practices that matter (multi-stage, non-root, distroless, pinning, .dockerignore, scanning, rootless); the control plane (API server, etcd, scheduler, controller manager) and nodes (kubelet, kube-proxy, containerd over CRI); the declarative model; Pod, Deployment, ReplicaSet, StatefulSet, DaemonSet, Job and CronJob with their exact knobs; ConfigMap, Secret and Downward API; requests, limits and QoS classes; scheduling (affinity, taints, topology spread, PodDisruptionBudget, priority and preemption); startup, liveness and readiness probes and their traps; restart backoff, eviction and node pressure; SIGTERM, preStop and terminationGracePeriodSeconds; HPA, VPA, KEDA, Cluster Autoscaler and Karpenter; Service types, EndpointSlices, kube-proxy modes, Ingress controllers, Gateway API and NetworkPolicy; PV, PVC, StorageClass and CSI; rolling, blue/green and canary with Argo Rollouts or Flagger; GitOps with Argo CD or Flux; Helm and Kustomize; RBAC, ServiceAccounts, IRSA/Workload Identity, Pod Security Standards, seccomp and Secret encryption at rest; Go and Laravel 13 (Octane/FrankenPHP, Horizon, scheduler, migrations) in pods; and when not to use Kubernetes at all. Learning goal: Write a Dockerfile and a set of manifests for a Go service and a Laravel 13 app that start safely, report the right probe, survive a rolling update and a node drain without a single 502, scale on the right metric, keep secrets and privileges small, and explain for each object which controller reconciles it and what happens when that controller, the node or the network fails.
This chapter sits in the Observability & Operations group and owns the system-level picture of running workloads on containers and Kubernetes: which object to use, which knob protects which failure, and the numbers that make a rollout or a shutdown safe. Neighbours own the mechanics: packet paths, CNI, CoreDNS and the iptables rules in Kubernetes Networking and the container networking model in Docker Networking; the scaling decision (vertical vs horizontal, USL, autoscaling policy) in Scaling Strategies; balancing algorithms in Load Balancing; sidecars and mesh traffic in Service Mesh & the Sidecar Pattern; functions in Serverless & Event-Driven Compute; metrics, logs and traces in Observability; certificates in pods in TLS in Practice; secrets management in Cryptography in Practice; process signals in Go in OS Processes, Signals & Graceful Shutdown.
Page map
Everything in one minute
The container side.
| Thing | In plain words | Tiny example | What it gives you | Trap |
|---|---|---|---|---|
| Namespace (Linux) | What a process can see | Own PID 1, own network stack, own mount table | Isolation of view | Not a security boundary on its own; shares the kernel |
| cgroup (v2) | What a process may use | memory.max = 512M, cpu.max = 50000 100000 | Limits and accounting | OOM kill when memory exceeds the limit |
| Image | A filesystem snapshot plus run config | shop:1.42.0 = 6 layers + config JSON | Same bytes on laptop, CI and prod | Mutable tags; huge images; secrets baked in |
| Layer | One tar of file changes | COPY vendor/ /app/vendor | Cache and dedup | Deleting a file in a later layer does not shrink the image |
| Registry | Where images live | registry.example.com/shop@sha256:... | Distribution, immutability by digest | Pull rate limits, private auth |
| Multi-stage build | Build in one image, ship from another | Go toolchain stage, distroless runtime stage | Small, few CVEs | Forgetting runtime files (CA certs, tzdata) |
The Kubernetes objects.
| Object | In plain words | Reconciled by | Use for | Key knobs |
|---|---|---|---|---|
| Pod | One or more containers sharing network and volumes | kubelet | The unit of scheduling | restartPolicy, probes, terminationGracePeriodSeconds |
| ReplicaSet | Keep N identical pods | ReplicaSet controller | Rarely directly | replicas, selector |
| Deployment | Versioned ReplicaSets with rollouts | Deployment controller | Stateless services | maxSurge, maxUnavailable, progressDeadlineSeconds |
| StatefulSet | Pods with stable names and own disks | StatefulSet controller | Databases, brokers, quorum systems | serviceName, volumeClaimTemplates, podManagementPolicy, partition |
| DaemonSet | One pod per (matching) node | DaemonSet controller | Log shippers, CNI and CSI agents | updateStrategy, tolerations |
| Job / CronJob | Run to completion, optionally on a schedule | Job / CronJob controllers | Migrations, batch, reports | backoffLimit, parallelism, ttlSecondsAfterFinished, concurrencyPolicy |
| Service | Stable name and virtual IP for ready pods | EndpointSlice controller + kube-proxy | Every network consumer | type, selector, ports |
| Ingress / Gateway | HTTP routing from outside | An Ingress controller / Gateway implementation | North-south traffic | host, path, TLS; HTTPRoute |
| HPA | Change replica count from metrics | HPA controller (every 15 s) | Elastic stateless tiers | minReplicas, maxReplicas, behavior |
| PodDisruptionBudget | Floor during voluntary disruption | Eviction API | Drains, node upgrades | minAvailable / maxUnavailable |
The self-healing and safety knobs, with defaults.
| Knob | Default | Protects against | Typical production value |
|---|---|---|---|
maxSurge / maxUnavailable | 25% / 25% | Capacity loss during rollout | 25% / 0 for zero-downtime web tiers |
progressDeadlineSeconds | 600 | Rollouts stuck silently | 600, alert on ProgressDeadlineExceeded |
revisionHistoryLimit | 10 | Being unable to roll back | 10 |
Probe periodSeconds / timeoutSeconds / failureThreshold | 10 / 1 / 3 | Wedged or not-yet-ready pods | Readiness 5 / 1 / 3; liveness 10 / 2 / 3 |
| Container restart backoff | 10 s doubling, capped at 300 s, reset after 10 min clean run | Crash storms | Not configurable per pod; fix the crash |
Job backoffLimit | 6 (retries 10 s, 20 s, 40 s ... capped at ten minutes) | Retrying a broken job forever | 2 to 4 for migrations |
terminationGracePeriodSeconds | 30 | Requests cut at shutdown | 30 to 60 for web; longest job for workers |
| HPA sync period / tolerance / scale-down window | 15 s / 0.1 / 300 s | Flapping | Keep defaults, tune behavior |
| kubelet hard eviction | memory.available<100Mi, nodefs.available<10%, imagefs.available<15%, nodefs.inodesFree<5% | Node running out | Reserve system-reserved / kube-reserved |
Why it exists
Before containers, a deploy meant "copy files to a server that already has the right PHP, the right extensions, the right libc and the right cron entries". Every server drifted. Containers fix the packaging problem: the image carries the userland, the process sees only its own filesystem and network, and the kernel enforces resource limits. Once you have hundreds of such processes, you get the second problem: someone has to decide where each runs, restart it when it dies, move it when its machine dies, give it a stable address, roll out a new version without downtime and scale it with load. Doing that by hand or with scripts is what Kubernetes replaces with a database of desired state and a set of control loops.
| Without an orchestrator | With Kubernetes |
|---|---|
| You pick a server per process | The scheduler picks a node from requests, affinity, taints and spread |
| A crashed process stays dead until monitoring pages you | The kubelet restarts it with backoff; a controller replaces lost pods |
| A dead server means manual migration | The node controller marks it, pods are recreated elsewhere |
| Deploys are scripts that stop and start things | A Deployment rolls out within maxSurge/maxUnavailable and can roll back |
| Load balancer membership is edited by hand | Services track ready pods through EndpointSlices |
| Scaling is a ticket | HPA, KEDA and node autoscalers react in seconds to minutes |
| Configuration lives on the box | ConfigMaps, Secrets and the Downward API inject it |
| Simple, few moving parts | A distributed system of its own: control plane, etcd, CNI, CSI, controllers, upgrades every few months |
The everyday picture used through the page. A container is a shipping container: a standard box whose contents the port does not care about. Kubernetes is the harbour master's office. You never tell a crane driver "move box 17 to ship B"; you file a manifest that says "ship B must carry 12 boxes of type web". Clerks (controllers) keep comparing the manifest with what they see on the docks and dispatch cranes (kubelets) to fix any difference. If a clerk goes home sick, the next clerk reads the same manifest and continues. Cranes that report a box as damaged (failed probe) get it replaced; boxes that are not yet sealed (not ready) are not loaded for customers.
Three common misunderstandings, up front
- "A container is a lightweight VM." It is a process on the host kernel with a different view of the world. There is no guest kernel; a kernel bug or a privileged container can reach the host. Use a VM or a sandbox runtime (gVisor, Kata Containers) when you need a hard boundary.
- "Kubernetes makes my app highly available." It restarts and reschedules; it does not make a single replica, a stateful process without replication, or a pod that ignores SIGTERM highly available. Availability still comes from replicas, spread across zones, readiness, graceful shutdown and PodDisruptionBudgets that you configure.
- "Liveness probe = health check, so check the database in it." Liveness answers "should this container be killed and restarted?" A database outage is not fixed by restarting every web pod at once; it is made worse. Dependencies belong in readiness, if anywhere.
Where it comes from
- Kernel isolation. Linux namespaces isolate what a process sees; the
namespaces(7)man page lists the types (Cgroup, IPC, Network, Mount, PID, Time, User, UTS). Linux control groups, percgroups(7), "allow processes to be organized into hierarchical groups whose usage of various types of resources can then be limited and monitored". The Borg/Omega paper credits Google with contributing "much of the container code to the Linux kernel" and notes that Solaris pioneered many of the enhancements that cgroups adopted. - Borg, Omega, Kubernetes. Burns, Grant, Oppenheimer, Brewer and Wilkes (ACM Queue, 2016) describe "three container-management systems over a decade" at Google. Kubernetes took from Borg the pod (Borg's "alloc"), labels, and the idea of a reconciliation controller loop, and from Omega a shared store of state with decoupled clients, but put an API server in front of the store "for object validation, defaulting, and versioning".
- Docker and OCI. Docker popularised the image + registry workflow (secondary knowledge, not quoted here). The Open Container Initiative image spec standardised the format: "an image manifest, an image index (optional), a set of filesystem layers, and a configuration". Kubernetes runs any OCI image through a CRI runtime such as containerd or CRI-O; the CRI is "the main gRPC protocol for the communication between the kubelet and Container Runtime", stable since v1.23.
- APIs that froze or retired. The Kubernetes docs now say "The Ingress API has been frozen" and recommend Gateway API instead; SIG Network announced that Ingress NGINX best-effort maintenance would continue "until March 2026" and then stop, with no further security fixes. kube-proxy's IPVS mode is deprecated since v1.35. At the time of writing the latest release is 1.37 (1.37.2, released 2026-10-13).
The concept catalogue
Every block follows the same order: in plain words, the common misunderstanding, the definition, a timeline, real scenarios, what each product or setting does, and the fix.
Containers: namespaces and cgroups Must-know
In plain words: a container is a normal process that the kernel lies to (namespaces: it sees its own PID 1, its own hostname, its own network interfaces and files) and keeps on a leash (cgroups: at most this much memory and CPU).
Common misunderstanding: "Containers are isolated like VMs, so running as root inside is fine." Root in a container is root on the host kernel unless user namespaces remap it; one kernel vulnerability or one privileged: true container gives the host away.
Definition: a container runtime (runc, called by containerd or CRI-O) creates a process with new Linux namespaces (Mount, PID, Network, UTS, IPC, User, Cgroup, Time), places it in a cgroup with limits (memory.max, cpu.max, pids.max in cgroup v2), mounts the image layers as its root filesystem through an overlay filesystem, drops capabilities and applies a seccomp profile. In Kubernetes all containers of a pod share the Network and IPC namespaces (that is why they talk over localhost) but have separate Mount namespaces.
What "docker run" / the kubelet + containerd do for one container
1 runtime pulls image layers by digest, unpacks them into the snapshotter (overlayfs)
2 runc: clone() with CLONE_NEWNS|NEWPID|NEWNET|NEWUTS|NEWIPC (+ NEWUSER if rootless/userns)
3 cgroup v2: write memory.max=536870912, cpu.max="100000 100000" for this container
4 pivot_root into the merged overlay; mount /proc, /dev, secrets, ConfigMap volumes
5 drop capabilities, apply seccomp RuntimeDefault, set UID 10001
6 exec the ENTRYPOINT: it becomes PID 1 inside the PID namespace
7 memory use reaches memory.max -> kernel OOM killer -> exit code 137, reason OOMKilledReal scenario: a PHP worker leaks memory and is OOM-killed at its 512 Mi limit while the node still has 20 GB free (the limit is per container, not per node); a Go service throttled by a cpu.max quota shows high p99 although average CPU is 40% (CFS throttling happens within each 100 ms period); two containers in one pod bind the same port and the second fails with address already in use because they share one network namespace.
| Mechanism | Docker Engine | Kubernetes (containerd / CRI-O) | Note |
|---|---|---|---|
| Memory limit | --memory | resources.limits.memory | Exceeding it means OOM kill |
| CPU limit | --cpus | resources.limits.cpu | CFS quota: throttling, never a kill |
| CPU share | --cpu-shares | resources.requests.cpu | Weight under contention; used by the scheduler |
| PID limit | --pids-limit | kubelet podPidsLimit | Stops fork bombs |
| User namespace | rootless mode, userns-remap | hostUsers: false in the pod spec | Root inside maps to an unprivileged host UID |
Fix / how to use it: run as a non-root UID, drop all capabilities, use seccompProfile: RuntimeDefault, a read-only root filesystem, and set memory limits from measured peak plus headroom. Networking details (veth pairs, bridges, iptables) live in Docker Networking.
Images, layers and the OCI spec Must-know
In plain words: an image is a pile of zip-like layers plus a small JSON file that says "run this command as this user with these environment variables". Each Dockerfile instruction that changes files adds a layer.
Common misunderstanding: "I deleted the .env file in the next step, so it is not in the image." Layers are additive; the file is still in the earlier layer, and anyone who pulls the image can extract it. The deletion is only a whiteout entry.
Definition: the OCI image spec defines an image as an image manifest, an optional image index (for multi-architecture images: linux/amd64, linux/arm64), a set of filesystem layers (tar changesets where removals are "whiteout" files) and a configuration (entrypoint, env, user, working dir). Every blob is addressed by its SHA-256 digest, so shop@sha256:4f1c... is immutable while shop:latest or even shop:1.42.0 is just a movable pointer.
Layer cache during a rebuild (Docker BuildKit)
1 FROM golang:1.24-bookworm cached
2 COPY go.mod go.sum ./ cached (files unchanged)
3 RUN go mod download cached
4 COPY . . MISS (one .go file changed)
5 RUN go build ... rebuilt
-> order instructions from least to most frequently changingReal scenario: a 1.2 GB image built FROM php:8.4 with build tools takes 40 s to pull on every new node, which is the real cold-start time of an autoscaled pod; a team tags :latest, two nodes pull at different times and run different code; an arm64 Graviton node pool fails with exec format error because only an amd64 image was pushed.
| Property | Tag | Digest |
|---|---|---|
| Example | shop:1.42.0 | shop@sha256:4f1c... |
| Can change after push | Yes | Never |
| Readable in manifests | Yes | Needs tooling (Renovate, Kustomize images:) |
Kubernetes imagePullPolicy default | IfNotPresent for a fixed tag, Always for :latest or no tag | IfNotPresent |
Fix / how to use it: build multi-arch with docker buildx build --platform linux/amd64,linux/arm64, deploy by immutable version tag plus digest, keep the image small, and never put secrets in any layer (use BuildKit --mount=type=secret for build-time credentials).
Dockerfile practices: multi-stage, non-root, distroless, pinning Must-know
In plain words: build in a big image that has compilers, copy only the result into a tiny image that has nothing else, run it as a normal user, and pin the base image so the same Dockerfile builds the same thing next week.
Common misunderstanding: "Alpine is always the smallest and safest base." Alpine uses musl libc, which changes DNS and some performance behaviour; for a static Go binary, distroless static or scratch is smaller still, and for PHP the official Debian-based images are the tested path.
Definition: Docker's own guidance: "With multi-stage builds, you use multiple FROM statements in your Dockerfile. Each FROM instruction can use a different base, and each of them begins a new stage of the build." "If a service can run without privileges, use USER to change to a non-root user." "Image tags are mutable", so "pin the image version to a specific digest". "Use a .dockerignore file" to keep the build context small. Distroless images "contain only your application and its runtime dependencies. They do not contain package managers, shells or any other programs".
Two builds of the same Go service
1 single stage, FROM golang:1.24 ~850 MB, shell, compilers, apt, root
2 multi-stage, distroless static ~10 MB, no shell, UID 65532, one binary
pull on a fresh node: tens of seconds vs about a second; scanner findings: many vs fewReal scenario: an incident responder cannot kubectl exec a shell into a distroless pod and uses kubectl debug -it pod/web --image=busybox --target=web (an ephemeral container) instead; a Laravel image that runs as root fails the Pod Security restricted profile on admission; a build context that includes node_modules and .git makes every build upload 600 MB.
| Practice | Why | Go | Laravel |
|---|---|---|---|
| Multi-stage | Ship only artefacts | golang build stage, distroless/static:nonroot runtime | composer and node stages, dunglas/frankenphp runtime |
Non-root USER | PSS restricted, smaller blast radius | UID 65532 | UID 10001, setcap -r on FrankenPHP for port 8000 |
Exec-form ENTRYPOINT/CMD | Your process is PID 1 and gets SIGTERM | ["/web"] | exec php artisan octane:frankenphp |
| Pin base images | Reproducible builds | golang:1.24-bookworm@sha256:... | dunglas/frankenphp:1-php8.4-bookworm@sha256:... |
.dockerignore | Small context, no secrets | .git, tests, .env | .git, node_modules, vendor, .env, storage/logs |
| Dependency layer first | Cache hits | COPY go.mod then go mod download | COPY composer.json composer.lock then composer install |
| No secrets in layers | Layers are public to pullers | BuildKit secret mounts | Runtime env from Secrets, never COPY .env |
Fix / how to use it: the Go and Laravel Dockerfiles in Go and Laravel apply every row. A good .dockerignore for the Go module:
.git
**/*_test.go
before/
Dockerfile
.dockerignore
*.md
.env
.env.*
coverage.outRegistries, image scanning and rootless builds Important
In plain words: a registry is the warehouse your cluster pulls from; a scanner reads the package list inside each image and tells you which ones have known vulnerabilities; rootless means the container engine itself does not run as root.
Common misunderstanding: "The scan was clean at build time, so the image is safe." New CVEs are published daily against packages that were fine yesterday; rescan what is running, not only what is being built.
Definition: a registry implements the OCI distribution API (Docker Hub, GitHub Container Registry, Amazon ECR, Google Artifact Registry, Azure Container Registry, Harbor). Scanners such as Trivy or Grype generate an SBOM and match packages against vulnerability databases; registries like ECR and Harbor can scan on push. Docker rootless mode runs "both the daemon and the container ... without root privileges", unlike userns-remap, where the daemon stays root. In-cluster builds use rootless BuildKit or Kaniko instead of mounting the Docker socket.
A supply-chain pipeline
1 CI builds image -> pushes registry.example.com/shop:1.42.0 (digest sha256:4f1c...)
2 trivy image --severity HIGH,CRITICAL --exit-code 1 shop:1.42.0 -> fail the build on findings
3 cosign sign registry.example.com/shop@sha256:4f1c...
4 admission policy (Kyverno / Sigstore policy-controller) admits only signed digests from the company registry
5 nightly: rescan running digests; open a PR bumping the base imageReal scenario: Docker Hub anonymous pull limits throttle a big scale-out until the cluster uses a pull-through cache; a pod is stuck in ImagePullBackOff with pull access denied because its namespace lacks imagePullSecrets for the private registry; a critical OpenSSL CVE is fixed by rebuilding twenty images on a patched base, which is only quick when every Dockerfile pins and bumps one base.
| Need | Option | Product |
|---|---|---|
| Managed registry | Cloud registry with IAM | Amazon ECR, Google Artifact Registry, Azure Container Registry |
| Self-hosted | Registry with scanning and replication | Harbor |
| Scan images | CLI in CI, operator in cluster | Trivy, Grype; Trivy Operator |
| Sign and verify | Keyless or key-based signatures | Sigstore cosign, policy-controller, Kyverno |
| Build without root | Rootless daemon or daemonless | Docker rootless mode, BuildKit rootless, Kaniko, Buildah |
Fix / how to use it: pull from one company registry (mirror upstream images), scan in CI and continuously, sign digests, admit only signed images, and give each namespace the minimal pull secret or use the cloud's node IAM role for ECR/Artifact Registry.
Control plane and nodes Must-know
In plain words: a few control-plane processes keep the list of what should run and decide where; on every worker machine an agent (the kubelet) makes it so, and kube-proxy wires up the virtual IPs.
Common misunderstanding: "If the control plane is down, my pods die." Running pods keep running and serving; what stops is change: no scheduling, no rescheduling after a node failure, no scaling, no new endpoints. That is why the control plane is replicated (3 or 5 etcd members) and why managed offerings (EKS, GKE, AKS) run it for you.
Definition: per the Kubernetes components page: kube-apiserver exposes the Kubernetes HTTP API and is the only component that reads and writes etcd, the consistent, highly available key-value store (Raft) for all API data; kube-scheduler "looks for Pods not yet bound to a node, and assigns each Pod to a suitable node" (filtering, then scoring); kube-controller-manager "runs controllers to implement Kubernetes API behavior" (Deployment, ReplicaSet, Job, EndpointSlice, Node, ServiceAccount controllers...); cloud-controller-manager (optional) integrates with the cloud (load balancers, routes, node lifecycle). On each node, the kubelet "ensures that Pods are running", runs probes and reports status; kube-proxy (optional when a CNI such as Cilium replaces it) programs Service rules; the container runtime (containerd, CRI-O) is driven by the kubelet over the CRI, a gRPC API.
kubectl apply -f deployment.yaml (3 replicas)
1 apiserver: authenticate -> RBAC authorize -> mutating admission -> validate -> validating admission -> write to etcd
2 Deployment controller (watch) sees new Deployment -> creates ReplicaSet web-7d9
3 ReplicaSet controller sees 0/3 pods -> creates 3 Pods (nodeName empty)
4 scheduler sees unbound Pods -> filter (resources, taints, affinity) -> score -> binds each to a node
5 kubelet on node A sees a Pod bound to it -> CRI RunPodSandbox, PullImage, CreateContainer, StartContainer
6 kubelet runs startup, then readiness probes -> sets Pod condition Ready=True
7 EndpointSlice controller adds the pod IP as ready -> kube-proxy on every node updates iptables/nftablesReal scenario: etcd's disk is slow, every write waits on fsync, and kubectl apply times out while traffic is fine; a node loses network, its pods are marked for eviction only after the toleration for node.kubernetes.io/unreachable (300 s by default) expires, so recovery takes about five minutes; an admission webhook that is down blocks every pod creation in the cluster because its failurePolicy is Fail.
| Component | Runs where | Failure impact | Managed offering |
|---|---|---|---|
| kube-apiserver | Control plane, replicated behind a LB | No changes, no watches; pods keep running | Run by EKS/GKE/AKS |
| etcd | Control plane, 3 or 5 members | Loss of quorum: API read-only or down | Run by the provider |
| kube-scheduler | Control plane, leader-elected | New pods stay Pending | Provider |
| kube-controller-manager | Control plane, leader-elected | No reconciliation (no replacement pods, no rollouts) | Provider |
| kubelet | Every node | Node NotReady; pods evicted after the toleration | You (node pools) |
| kube-proxy / CNI | Every node (DaemonSet) | Service traffic on that node breaks | Usually you, via add-ons |
| containerd | Every node | No new containers on that node | Node image |
Fix / how to use it: prefer a managed control plane; run at least three nodes across zones; set failurePolicy and timeouts deliberately on admission webhooks; monitor apiserver latency and etcd fsync durations. Leader election for the scheduler and controller manager is the same pattern as in Leader Election.
Declarative model and the reconciliation loop Must-know
In plain words: you do not tell Kubernetes what to do; you tell it what you want to exist. Controllers keep looking at what exists and nudge it towards what you wrote, forever.
Common misunderstanding: "kubectl apply deploys my app." It only stores a desired state in etcd and returns. Whether the rollout succeeds is decided later by controllers; check kubectl rollout status or the Deployment conditions.
Definition: the docs: "In Kubernetes, controllers are control loops that watch the state of your cluster, then make or request changes where needed. Each controller tries to move the current cluster state closer to the desired state." Every object has a spec (desired, written by you) and a status (observed, written by controllers). Controllers are level-triggered: they react to the current state, not to a missed or duplicated event, so restarting them is safe. Operators are the same pattern applied to your own Custom Resource Definitions (CRDs). Declarative management (kubectl apply, server-side apply, GitOps) is preferred over imperative commands (kubectl scale, kubectl edit) because the source of truth stays in Git.
Reconcile pass (simplified; see reconcile.go below)
1 observe: list pods with selector app=web -> 2 ready, 1 missing (node died)
2 compare: spec.replicas = 3, observed = 2
3 act: create 1 pod; do nothing else
4 controller crashes and restarts
5 observe again: 3 pods (1 not ready yet) -> nothing to do; no duplicate pod is createdReal scenario: someone runs kubectl scale deploy/web --replicas=10 during an incident and Argo CD sets it back to 3 a minute later because Git says 3 (good or bad depending on whether the HPA owns replicas); an operator for PostgreSQL (CloudNativePG, Zalando) reconciles a Cluster CRD into StatefulSets, Services and backups; a Deployment and an HPA both "own" replicas and fight unless the manifest omits spec.replicas.
| Style | Example | Source of truth | Drift |
|---|---|---|---|
| Imperative command | kubectl run, kubectl scale | Your shell history | Invisible |
| Imperative object config | kubectl create -f, kubectl replace -f | Files, but you choose the verb | Overwrites |
| Declarative | kubectl apply -f, server-side apply | Files, merged by field ownership | Detected by diff |
| GitOps | Argo CD, Flux | Git, applied continuously | Corrected automatically |
Fix / how to use it: keep manifests in Git, apply with server-side apply or GitOps, let exactly one owner write each field (HPA owns replicas; omit it from the Deployment), and watch status.conditions. The Go simulation of this loop is in Go.
Pods and the Pod lifecycle Must-know
In plain words: a pod is the smallest thing Kubernetes schedules: one main container (sometimes with helpers) that shares an IP and some disks, lives on one node, and is never moved, only replaced.
Common misunderstanding: "A pod that is Running is serving traffic." Running is a phase: at least one container started. Traffic follows the Ready condition, which depends on readiness probes. A pod can be Running and not Ready for its whole life.
Definition: "Pods follow a defined lifecycle, starting in the Pending phase, moving through Running if at least one of its primary containers starts OK, and then through either the Succeeded or Failed phases." Unknown means the node cannot be reached. Pod conditions are PodScheduled, PodReadyToStartContainers, Initialized, ContainersReady, Ready. Container states are Waiting (with reasons such as ContainerCreating, ImagePullBackOff, CrashLoopBackOff), Running, Terminated (with exitCode and reasons such as OOMKilled, Error, Completed). Init containers run to completion, in order, before app containers; sidecar containers are init containers with restartPolicy: Always that keep running alongside the app.
A pod from creation to traffic
1 Pending PodScheduled=False (no node fits: "0/6 nodes are available: 3 Insufficient cpu")
2 Pending PodScheduled=True ContainerCreating (pull image, mount volumes, CNI sets up IP)
3 Pending Initialized=False init container "wait-for-migrations" running
4 Running ContainersReady=False startup probe failing while warm-up runs
5 Running Ready=True readiness passes -> added to EndpointSlices
6 Running Ready=False readiness fails (draining or dependency) -> removed, not restarted
7 Succeeded/Failed containers exited and restartPolicy does not restart themReal scenario: a pod sits in Pending with 0/6 nodes are available: 6 node(s) didn't match pod anti-affinity rules; CreateContainerConfigError because a referenced Secret key does not exist; a sidecar log shipper keeps a Job pod alive forever when declared as an ordinary container instead of a native sidecar.
| Status you see | Meaning | First command |
|---|---|---|
Pending | Not scheduled or not started | kubectl describe pod -> Events |
ContainerCreating | Pulling, mounting, networking | Events: FailedMount, FailedCreatePodSandBox |
ImagePullBackOff / ErrImagePull | Wrong name, tag, auth or rate limit | Check image, imagePullSecrets |
CrashLoopBackOff | Container keeps exiting; restarts are delayed | kubectl logs --previous |
CreateContainerConfigError | Missing ConfigMap/Secret key | kubectl describe pod |
OOMKilled (exit 137) | Memory limit exceeded | Raise limit or fix leak |
Evicted | Node pressure or API eviction | kubectl describe pod, node conditions |
Running, 0/1 READY | Readiness failing | kubectl describe pod probe events |
Fix / how to use it: one main process per container, helpers as native sidecars, init containers only for short preconditions, and never create bare pods: use a controller so the pod is replaced when it disappears.
Deployments, ReplicaSets and rolling updates Must-know
In plain words: a Deployment says "run N copies of this pod template"; when you change the template it starts new copies and stops old ones a few at a time, so the service stays up.
Common misunderstanding: "The default rolling update is zero-downtime." With maxUnavailable: 25% up to a quarter of the replicas can be missing during the rollout, and without readiness probes and graceful shutdown "missing" includes "receiving traffic while starting or stopping". Zero-downtime is a property of probes + shutdown + maxUnavailable: 0.
Definition: a Deployment owns ReplicaSets, one per pod-template hash; the ReplicaSet owns pods. Strategy RollingUpdate (default) or Recreate. From the docs: "By default, it ensures that at least 75% of the desired number of Pods are up (25% max unavailable)" and "at most 125% of the desired number of Pods are up (25% max surge)". Percentages round up for maxSurge and down for maxUnavailable; both cannot be 0. minReadySeconds makes a new pod count as available only after it has been Ready that long. progressDeadlineSeconds (default 600) sets the condition Progressing=False with reason ProgressDeadlineExceeded; it does not roll back by itself. revisionHistoryLimit (default 10) keeps old ReplicaSets for kubectl rollout undo.
replicas=10, maxSurge=25% (3), maxUnavailable=25% (2): from k8ssim, see Lab
1 pass 0 create 3 new, delete 2 old total 11 ready 8 new 3 old 8
2 pass 1 create 2, delete 3 total 10 ready 8 new 5 old 5
3 pass 2 create 3, delete 2 total 11 ready 8 new 8 old 3
4 pass 3 create 2, delete 3 total 10 ready 8 new 10 old 0
5 pass 4 nothing total 10 ready 10 converged
broken image instead: stalls at 13 pods, 8 old ready, 5 new never ready; Progressing=False after 600 sReal scenario: a bad image rolls out and the rollout stalls with the old pods still serving (good), but nobody notices for an hour because no alert watches ProgressDeadlineExceeded; a two-replica Deployment with defaults (maxUnavailable rounds 25% of 2 down to 0, maxSurge rounds up to 1) is already zero-unavailable; Recreate is used for a single-writer app that must never have two versions running, accepting downtime.
| Setting | Effect | When |
|---|---|---|
maxSurge: 25%, maxUnavailable: 25% | Default, fast, some capacity loss | Large stateless fleets with headroom |
maxSurge: 1, maxUnavailable: 0 | One extra pod at a time, no capacity loss | Small web tiers, tight capacity |
maxSurge: 100%, maxUnavailable: 0 | Double, then drop old (blue/green-like inside one Deployment) | Fast rollouts with spare cluster capacity |
strategy: Recreate | Stop all, then start all | Singletons, incompatible schema versions |
minReadySeconds: 10 | New pod must stay Ready 10 s | Catch pods that pass readiness and then crash |
kubectl rollout undo deploy/web | Back to previous ReplicaSet | Fast rollback, needs history |
Fix / how to use it:
apiVersion: apps/v1
kind: Deployment
metadata: { name: web, namespace: shop }
spec:
# replicas omitted: the HPA owns it
revisionHistoryLimit: 10
progressDeadlineSeconds: 600
minReadySeconds: 5
strategy:
type: RollingUpdate
rollingUpdate: { maxSurge: 25%, maxUnavailable: 0 }
selector: { matchLabels: { app: web } }
template:
metadata: { labels: { app: web } }
spec:
terminationGracePeriodSeconds: 30
containers:
- name: web
image: registry.example.com/web:1.42.0
ports: [{ name: http, containerPort: 8080 }]StatefulSets: stable identity and own disks Important
In plain words: a StatefulSet is for pods that are not interchangeable: db-0 is always db-0, comes back with the same name and the same disk, and they start and update in order.
Common misunderstanding: "Putting PostgreSQL in a StatefulSet makes it highly available." The StatefulSet gives names, disks and ordering; replication, failover and backups come from the database itself or from an operator (CloudNativePG, Strimzi for Kafka, the Redis operator of your choice).
Definition: each pod gets an ordinal (web-0, web-1...), a stable DNS name through a headless Service (clusterIP: None, named in spec.serviceName) such as db-0.db.shop.svc.cluster.local, and its own PersistentVolumeClaim from volumeClaimTemplates that survives pod rescheduling. podManagementPolicy: OrderedReady (default) creates pods 0..N-1 one at a time, each Ready before the next, and deletes in reverse; Parallel does not wait. Updates: RollingUpdate from the highest ordinal down, with partition to update only ordinals >= partition (a canary for stateful sets) and maxUnavailable; OnDelete; and Recreate behind the StatefulSetRecreateStrategy feature gate. persistentVolumeClaimRetentionPolicy decides whether PVCs are deleted on scale-down or deletion (default: retained).
Scale a 3-member StatefulSet (OrderedReady) and update it
1 create db-0 -> Ready -> create db-1 -> Ready -> create db-2
2 update template: db-2 replaced -> Ready -> db-1 -> Ready -> db-0
3 partition: 2 -> only db-2 gets the new version; db-0, db-1 stay (stateful canary)
4 scale to 2 -> db-2 deleted; PVC data-db-2 kept (Retain) -> scale back to 3 reattaches itReal scenario: a three-node etcd or ZooKeeper ensemble where peers address each other by stable DNS; a Kafka broker that must come back with its own log directory; an OrderedReady rollout stuck because db-1 never becomes Ready and the docs warn this "requires manual intervention to repair".
| Need | Deployment | StatefulSet |
|---|---|---|
| Pod names | Random suffix | Ordinal, stable |
| DNS per pod | No | Yes, via headless Service |
| Storage | Shared claim or none | One PVC per pod from a template |
| Start/stop order | Any | Ordered (or Parallel) |
| Rollout canary | Separate Deployment or Argo Rollouts | partition |
Fix / how to use it: run stateful products through a mature operator, or use the managed service (RDS, Cloud SQL, ElastiCache, MSK) and keep the cluster stateless; see storage caution.
DaemonSets: one pod per node Good to know
In plain words: a DaemonSet puts exactly one copy of a pod on every node (or every node matching a selector), and a new node gets one automatically.
Common misunderstanding: "My app should be a DaemonSet so it scales with nodes." Node count is the wrong scaling signal for an application; DaemonSets are for node-level agents.
Definition: the DaemonSet controller creates one pod per eligible node; it usually tolerates taints such as node.kubernetes.io/not-ready so agents run even on unhealthy nodes. updateStrategy: RollingUpdate (with maxUnavailable, maxSurge) or OnDelete.
1 Karpenter adds node ip-10-0-3-7
2 DaemonSet controller: node matches -> create fluent-bit-x8k on it
3 node drained -> DaemonSet pods are ignored by "kubectl drain --ignore-daemonsets"Real scenario: Fluent Bit or Vector shipping logs, the Cilium or Calico agent, a CSI node plugin, node-exporter for Prometheus; every DaemonSet pod is a tax on every node, which matters with many small nodes.
| Agent | Typical product |
|---|---|
| Logs | Fluent Bit, Vector, OpenTelemetry Collector (agent mode) |
| Networking | Cilium, Calico, kube-proxy |
| Storage | CSI node plugins (EBS, GCE PD, Ceph) |
| Metrics | node-exporter |
Fix / how to use it: set small requests and a priorityClassName: system-node-critical for agents the node cannot live without.
Jobs and CronJobs Important
In plain words: a Job runs a pod until it succeeds (with a limited number of retries); a CronJob creates a Job on a schedule, like crontab.
Common misunderstanding: "A CronJob runs exactly once per schedule." The docs warn that "in certain circumstances, a single CronJob can create multiple concurrent Jobs", and a run can also be skipped (controller down, startingDeadlineSeconds exceeded). Jobs must be idempotent.
Definition: Job fields: completions, parallelism, completionMode: Indexed, backoffLimit ("set by default to 6"; failed pods are recreated "with an exponential back-off delay (10s, 20s, 40s ...) capped at ten minutes"), backoffLimitPerIndex, podFailurePolicy (fail fast on exit code, ignore disruptions), activeDeadlineSeconds, ttlSecondsAfterFinished (delete the finished Job and its pods), restartPolicy: Never | OnFailure. CronJob fields: schedule (cron syntax), timeZone, concurrencyPolicy (Allow default, Forbid, Replace), startingDeadlineSeconds, suspend, successfulJobsHistoryLimit (default 3) and failedJobsHistoryLimit (default 1).
Migration Job with backoffLimit: 2
1 pod 1 runs "php artisan migrate --force" -> exit 1 (lock timeout)
2 wait 10 s -> pod 2 -> exit 1
3 wait 20 s -> pod 3 -> exit 1
4 Job condition Failed, reason BackoffLimitExceeded -> the pipeline stops the rolloutReal scenario: database migrations once per release (not in every web pod's entrypoint); a nightly report as a CronJob with concurrencyPolicy: Forbid so a slow run is not overlapped; a fan-out image-processing Job with parallelism: 20 and completionMode: Indexed where each pod reads JOB_COMPLETION_INDEX.
| Knob | Default | Use |
|---|---|---|
backoffLimit | 6 | 2 for migrations, higher for flaky batch |
parallelism / completions | 1 / 1 | Work queues, indexed fan-out |
activeDeadlineSeconds | none | Hard wall-clock limit |
ttlSecondsAfterFinished | none | Garbage-collect finished Jobs |
concurrencyPolicy | Allow | Forbid for reports, Replace for "latest wins" |
startingDeadlineSeconds | none | Skip runs that are too late to matter |
Fix / how to use it: see the migration Job and scheduler CronJob in Laravel.
ConfigMaps, Secrets and the Downward API Must-know
In plain words: keep the image the same in every environment and inject settings at run time: ordinary settings from a ConfigMap, passwords from a Secret, and facts about the pod itself (its name, node, limits) from the Downward API.
Common misunderstanding: "Secrets are encrypted." They are base64-encoded. The docs: "Kubernetes Secrets are, by default, stored unencrypted in the API server's underlying data store (etcd)", and "anyone who is authorized to create a Pod in a namespace can use that access to read any Secret in that namespace".
Definition: ConfigMap and Secret both hold key/value data; a ConfigMap "cannot exceed 1 MiB" and "Individual Secrets are limited to 1MiB in size". They reach a container as environment variables (env.valueFrom, envFrom) or as files in a volume. Environment variables are read once at start; mounted files are updated by the kubelet after a delay (not for subPath mounts), and the app must re-read them. immutable: true protects against accidental edits and reduces apiserver load. The Downward API exposes metadata.name, metadata.namespace, spec.nodeName, status.podIP, labels, annotations and resources.limits.* through fieldRef and resourceFieldRef.
Change a ConfigMap value
1 kubectl apply: LOG_LEVEL=debug
2 pods using env: still "info" until restarted
3 pods using a volume: file changes after the kubelet sync (seconds to a minute)
4 kubectl rollout restart deploy/web -> new pods read the new env
better: put a hash of the ConfigMap in a pod annotation (Helm, Kustomize configMapGenerator) so a change triggers a rolloutReal scenario: a Laravel app with APP_KEY, DB_PASSWORD from a Secret and APP_ENV, CACHE_STORE from a ConfigMap; a Go service that sets GOMEMLIMIT from resourceFieldRef: limits.memory; secrets synced from AWS Secrets Manager or HashiCorp Vault with the External Secrets Operator or the Secrets Store CSI Driver.
| Option | Good for | Limit |
|---|---|---|
| ConfigMap as env | Twelve-factor settings | Needs restart to change |
| ConfigMap as volume | Config files, hot reload | App must watch the file |
| Secret | Credentials, TLS keys | base64 only; enable encryption at rest and RBAC |
| External Secrets / CSI driver | Source of truth in a vault | Extra controller |
| Downward API | Pod name, node, limits | Read-only facts |
Fix / how to use it:
env:
- name: POD_NAME
valueFrom: { fieldRef: { fieldPath: metadata.name } }
- name: NODE_NAME
valueFrom: { fieldRef: { fieldPath: spec.nodeName } }
- name: GOMEMLIMIT
valueFrom: { resourceFieldRef: { resource: limits.memory } }
- name: DB_PASSWORD
valueFrom: { secretKeyRef: { name: web-db, key: password } }
envFrom:
- configMapRef: { name: web-config }Requests, limits and QoS classes Must-know
In plain words: a request is what the scheduler reserves for you; a limit is the ceiling the kernel enforces. Together they decide your pod's QoS class, which decides who gets evicted first when a node runs short.
Common misunderstanding: "Set CPU limits equal to requests everywhere for safety." A CPU limit throttles even when the node is idle, which inflates tail latency; many teams set CPU requests, no CPU limit, and a memory limit. A memory limit, on the other hand, is a kill switch, so it must be above real peak.
Definition: requests drive scheduling (the sum of requests on a node may not exceed its allocatable) and CPU weight; limits are cgroup ceilings (CPU throttled, memory OOM-killed). QoS: Guaranteed when every container has CPU and memory limits and requests equal to them; BestEffort when no container has any CPU or memory request or limit; Burstable otherwise. Under node pressure the kubelet evicts "BestEffort or Burstable pods where the usage exceeds requests" first, ordered by priority and overuse; "Guaranteed pods and Burstable pods where the usage is less than requests are evicted last". LimitRange sets per-namespace defaults; ResourceQuota caps the namespace total.
Node with 4 GiB allocatable, memory pressure
1 pod A BestEffort using 600 Mi -> evicted first (no request at all)
2 pod B Burstable, request 256 Mi, using 700 Mi -> next (usage above request)
3 pod C Guaranteed 1 Gi/1 Gi, using 900 Mi -> last
4 a container above its own limit is OOM-killed by the kernel regardless of class (exit 137)Real scenario: pods without requests are packed onto one node by the scheduler and then evict each other; a Go service with limits.cpu: 500m on a 16-core node runs with a large default GOMAXPROCS on older Go versions and is throttled hard (Go 1.25+ reads the cgroup CPU limit; check your version); a JVM or PHP worker with a heap larger than the container limit is OOM-killed under load.
| Setting | Scheduler | Kernel | QoS effect |
|---|---|---|---|
| No requests, no limits | Reserves nothing | Unlimited up to node | BestEffort |
| Requests only | Reserves request | CPU weight, no ceiling | Burstable |
| Requests < limits | Reserves request | Ceilings at limits | Burstable |
| Requests = limits (CPU and memory) | Reserves limit | Ceilings at limits | Guaranteed |
Fix / how to use it: measure, then set CPU request near p50 usage, memory request near steady state, memory limit above peak; use VPA in Off mode for recommendations; the classifier in qos.go reproduces the rules above.
Scheduling: affinity, taints, topology spread, priority Important
In plain words: you can tell the scheduler where pods may go (node affinity), where they may not (taints unless tolerated), which pods should avoid each other (anti-affinity), how evenly to spread them (topology spread), and who wins when there is not enough room (priority and preemption).
Common misunderstanding: "Three replicas means three zones." Without a topology spread constraint or anti-affinity, the scheduler may put all three on one node in one zone because that node scores best.
Definition: nodeSelector and node affinity (requiredDuringSchedulingIgnoredDuringExecution, preferred...) match node labels such as topology.kubernetes.io/zone or karpenter.sh/capacity-type. Pod affinity/anti-affinity match labels of other pods within a topologyKey. A taint (key=value:NoSchedule | PreferNoSchedule | NoExecute) repels pods that lack a matching toleration; NoExecute also evicts running ones after tolerationSeconds. Topology spread constraints use maxSkew, topologyKey, whenUnsatisfiable: DoNotSchedule | ScheduleAnyway, labelSelector, minDomains, matchLabelKeys. PriorityClass gives a pod a priority; a pending high-priority pod can preempt (evict) lower-priority ones; Kubernetes ships system-cluster-critical and system-node-critical.
Spread 6 web pods over 3 zones with maxSkew 1
1 zone a: 2 zone b: 2 zone c: 1 -> next pod must go to c (skew would become 2 elsewhere)
2 zone c full and whenUnsatisfiable=DoNotSchedule -> pod Pending, Karpenter adds a node in c
3 with ScheduleAnyway -> placed in a or b, skew 2 toleratedReal scenario: GPU nodes tainted nvidia.com/gpu=present:NoSchedule so only ML pods land there; a batch PriorityClass with preemptionPolicy: Never so jobs never kick out web pods; spot nodes labelled and tainted so only interruption-tolerant workers use them.
| Tool | Expresses | Hard or soft |
|---|---|---|
nodeSelector | Must run on labelled nodes | Hard |
| Node affinity | Must / prefer nodes with labels | Both |
| Pod anti-affinity | Avoid nodes/zones with my peers | Both |
| Taints and tolerations | Nodes repel pods unless tolerated | Hard (NoSchedule), soft (PreferNoSchedule) |
| Topology spread constraints | Even spread across zones/nodes | DoNotSchedule / ScheduleAnyway |
| PriorityClass | Who wins and may preempt | Ordering |
Fix / how to use it:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector: { matchLabels: { app: web } }
matchLabelKeys: [pod-template-hash]
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
labelSelector: { matchLabels: { app: web } }PodDisruptionBudgets Important
In plain words: a PDB says "during planned maintenance, never take more than this many of my pods away at once".
Common misunderstanding: "A PDB protects me from node crashes." It only applies to voluntary disruptions that go through the Eviction API (kubectl drain, Cluster Autoscaler and Karpenter consolidation, node upgrades). A node that dies, an OOM kill or a kubectl delete pod ignores it.
Definition: spec.minAvailable or spec.maxUnavailable (count or percent) plus a selector. An eviction that would violate it is refused with 429 Too Many Requests and the drain retries (kubectl prints "Cannot evict pod as it would violate the pod's disruption budget"). unhealthyPodEvictionPolicy: AlwaysAllow lets already-unhealthy pods be evicted so a broken app does not block node upgrades.
kubectl drain node-a (web has 3 replicas, PDB maxUnavailable: 1)
1 evict web-1 -> allowed (2 left) -> replacement scheduled on node-b
2 evict web-2 -> 429 until the replacement is Ready
3 replacement Ready -> evict web-2 allowedReal scenario: a managed node-group upgrade (EKS, GKE) stalls for an hour because a PDB has minAvailable: 100% or a single-replica Deployment has minAvailable: 1; Karpenter respects PDBs during consolidation.
| PDB | With 3 replicas | Effect on drain |
|---|---|---|
maxUnavailable: 1 | 1 at a time | Good default |
minAvailable: 2 | Same as above | Same |
minAvailable: 100% | Never | Blocks drains forever |
1 replica + minAvailable: 1 | Never | Blocks; run 2 replicas instead |
Fix / how to use it: every multi-replica service gets maxUnavailable: 1 (or 10% for big fleets) and at least two replicas.
Probes: startup, liveness, readiness Must-know
In plain words: three questions the kubelet keeps asking your container: "have you finished starting?" (startup), "are you stuck and need a restart?" (liveness), "may I send you traffic right now?" (readiness).
Common misunderstanding: "Readiness and liveness should hit the same /health endpoint." Then a failing dependency both removes the pod from traffic and restarts it, and a slow request queue looks like a deadlock. They answer different questions and need different endpoints.
Definition: mechanisms httpGet (200–399 is success), tcpSocket, grpc, exec. Fields and defaults: initialDelaySeconds 0, periodSeconds 10, timeoutSeconds 1, successThreshold 1 (must be 1 for liveness and startup), failureThreshold 3, plus a probe-level terminationGracePeriodSeconds. Liveness and readiness do not run until the startup probe has succeeded; a startup or liveness failure restarts the container, a readiness failure only marks the pod NotReady and removes it from EndpointSlices. The docs: if your container usually starts in more than initialDelaySeconds + failureThreshold × periodSeconds, "you should specify a startup probe".
Liveness trap vs correct split (DB outage at t=0)
1 t=0 PostgreSQL failover starts (30 s)
2 t=10 /health checks DB in liveness -> fail 1
3 t=30 fail 3 -> kubelet restarts ALL web pods; cold start, OPcache empty, Octane boot
4 t=31 DB back; every pod is still starting -> full outage for another 40 s
with the split: readiness fails -> pods leave the Service -> 503 from ingress for 30 s
-> readiness passes -> traffic back instantly, nothing restartedReal scenario: a Laravel pod that needs 60 s to warm up is killed by a liveness probe at 30 s and never starts (CrashLoopBackOff); a Go service with timeoutSeconds: 1 fails liveness under GC pressure and is restarted exactly when it is busiest; a readiness probe that checks a downstream service causes a cascading removal of every pod (see Cascading Failures).
| Probe | Question | On failure | Should check | Must not check |
|---|---|---|---|---|
| Startup | Finished booting? | Restart after threshold | Same cheap endpoint as liveness | Long dependency chains |
| Liveness | Wedged? | Container restart | Process can make progress (event loop, worker heartbeat) | Databases, caches, other services |
| Readiness | Can serve now? | Removed from endpoints | Draining flag, local dependencies the pod truly cannot serve without | Shared downstream services that every pod depends on equally (optional) |
Fix / how to use it:
startupProbe: { httpGet: { path: /startupz, port: http }, periodSeconds: 2, failureThreshold: 60 } # up to 120 s
livenessProbe: { httpGet: { path: /livez, port: http }, periodSeconds: 10, timeoutSeconds: 2, failureThreshold: 3 }
readinessProbe: { httpGet: { path: /readyz, port: http }, periodSeconds: 5, timeoutSeconds: 1, failureThreshold: 2 }Restart policies, CrashLoopBackOff, eviction and node pressure Must-know
In plain words: when a container exits, the kubelet restarts it in place with growing pauses; when a whole node is in trouble, the kubelet or the control plane removes pods so that controllers can recreate them elsewhere.
Common misunderstanding: "CrashLoopBackOff is an error type." It is a waiting state: the container crashed and the kubelet is waiting out the backoff before the next try. The cause is in kubectl logs --previous and the last Terminated state.
Definition: restartPolicy is Always (Deployments require it), OnFailure or Never (Jobs). "The kubelet restarts them with an exponential backoff delay (10s, 20s, 40s, …), that is capped at 300 seconds (5 minutes). Once a container has executed for 10 minutes without any problems, the kubelet resets the restart backoff timer." Node-pressure eviction: the kubelet watches signals and evicts pods when a hard threshold is crossed (defaults memory.available<100Mi, nodefs.available<10%, imagefs.available<15%, nodefs.inodesFree<5%), sets node conditions MemoryPressure, DiskPressure, PIDPressure and taints the node; with hard thresholds "the kubelet uses a 0s grace period". API-initiated eviction (drain) respects PDBs and the grace period. A node that stops reporting gets node.kubernetes.io/unreachable, and pods without a longer toleration are evicted after 300 s.
A container that exits 1 on start
1 t=0 start -> exit 1 -> restart immediately
2 t=10s second start -> exit 1 (backoff 10 s)
3 t=30s third (20 s) ... t=70s (40 s) ... then 80, 160, 300, 300 s
4 STATUS CrashLoopBackOff, RESTARTS 7 -> kubectl logs web-x --previousReal scenario: a log-heavy pod fills the node disk, DiskPressure evicts BestEffort pods and new pods are refused; a node kernel panic, pods return elsewhere after about five minutes unless tolerationSeconds is lowered; an app that exits 0 on a fatal config error loops forever under Always.
| Event | Who acts | PDB respected | Grace period |
|---|---|---|---|
| Container exits | kubelet, in place | No | n/a |
| Liveness failure | kubelet restarts container | No | Pod or probe-level grace |
| Hard eviction (node pressure) | kubelet | No | 0 s |
| Soft eviction | kubelet | No | evictionMaxPodGracePeriod |
kubectl drain / autoscaler | Eviction API | Yes | Pod grace |
| Preemption | Scheduler | Best effort | Pod grace |
| Node unreachable | Node lifecycle controller | No | After toleration (300 s) |
Fix / how to use it: set requests so pods are not BestEffort, keep logs on stdout (rotated by the kubelet) rather than on local disk, set ephemeral-storage requests, and alert on restart counts and CrashLoopBackOff.
Graceful shutdown: SIGTERM, preStop, grace period Must-know
In plain words: when a pod is told to stop, Kubernetes removes it from load balancing and sends it SIGTERM at roughly the same time; your process must keep serving for a few seconds, finish what it has, and exit before the deadline, or it is killed.
Common misunderstanding: "Kubernetes removes the pod from the Service before sending SIGTERM." The docs: "At the same time as the kubelet is starting graceful shutdown of the Pod, the control plane evaluates whether to remove that shutting-down Pod from EndpointSlice objects". kube-proxy on every node, ingress controllers and cloud load balancers then catch up at their own speed, so an app that exits on SIGTERM drops requests that are still being routed to it.
Definition: on deletion the kubelet starts the grace countdown (terminationGracePeriodSeconds, default 30), runs the preStop hook (exec, httpGet or sleep) and "the hook must complete before the TERM signal to stop the container can be sent"; the countdown includes the hook. Then the container gets its stop signal (SIGTERM unless the image or lifecycle.stopSignal says otherwise). "When the grace period expires, if there is still any container running in the Pod, the kubelet triggers forcible shutdown. The container runtime sends SIGKILL". Exit code 137 is 128 + 9 (SIGKILL), 143 is 128 + 15 (SIGTERM).
Budget for a web pod (grace 30 s)
1 preStop sleep 5 5 s endpoints converge while the app still serves
2 SIGTERM -> readiness 503 0 s (already out of the Service)
3 Shutdown(ctx, 20 s) <=20 s in-flight requests finish, keep-alives closed
4 margin 2 s flush logs, exit
total 27 s <= 30 s; a 10 s preStop with a 20 s shutdown needs 37 s -> SIGKILL riskReal scenario: every deploy produces a burst of 502s at the NGINX ingress because pods exit on SIGTERM immediately; a shell-form CMD php artisan ... runs under /bin/sh, which does not forward SIGTERM, so the app is SIGKILLed after 30 s every time; a queue worker processing 2-minute jobs is killed mid-job because grace is 30 s.
| Workload | preStop | Grace | App on SIGTERM |
|---|---|---|---|
| Go HTTP | sleep 5 or in-app drain delay | 30 s | Fail readiness, wait, Shutdown(ctx) |
| Laravel Octane | php artisan app:prepare-shutdown --wait=5 | 30 s | Octane stops workers gracefully |
| Horizon | php artisan horizon:terminate | Longest job timeout + margin | Finish current jobs, stop |
| gRPC | sleep 5 | 30 s | GracefulStop() |
| Long batch | none | activeDeadlineSeconds and checkpointing | Save progress, exit non-zero to be retried |
Fix / how to use it: the Go lifecycle.Run and the Laravel PrepareShutdown command implement this budget; exec-form entrypoints keep your process as PID 1. The signal side of Go is in OS Processes, Signals & Graceful Shutdown.
Autoscaling: HPA, VPA, KEDA, Cluster Autoscaler, Karpenter Must-know
In plain words: the HPA changes how many pods you have, the VPA changes how big each pod is, KEDA lets the HPA scale on queue length (down to zero), and Cluster Autoscaler or Karpenter add and remove the machines those pods need.
Common misunderstanding: "HPA on CPU is enough." CPU utilization is relative to the request; with no request the HPA cannot compute it, and for I/O-bound PHP or queue workers CPU may never move while latency or backlog explodes.
Definition: the HPA controller runs every 15 s (--horizontal-pod-autoscaler-sync-period) and computes desiredReplicas = ceil(currentReplicas × currentMetricValue / desiredMetricValue), skipping changes within a 0.1 tolerance; metric types Resource (CPU, memory from metrics-server), ContainerResource, Pods and Object (custom metrics via an adapter such as Prometheus Adapter), External (KEDA, cloud metrics). behavior sets policies and stabilization windows (default scale-down window 300 s, scale-up 0 s). VPA update modes are Off, Initial, Recreate, InPlaceOrRecreate, InPlace; do not let VPA and HPA act on the same CPU/memory metric. KEDA "feeds the HPA with external metrics" and scales "all the way to zero if needed". Cluster Autoscaler adds nodes when pods are Pending for lack of capacity and removes underused nodes; Karpenter provisions right-sized nodes directly from pending pods using NodePools and NodeClasses and consolidates them. The policy and the arithmetic are in Scaling Strategies.
Spike on a Laravel queue (KEDA on a Redis list) with Karpenter
1 t=0 backlog 0 -> 0 worker pods (scaled to zero)
2 t+30s KEDA polls: 1,200 jobs, target 100 per pod -> HPA desired 12
3 t+31s 12 pods Pending: no capacity
4 t+75s Karpenter launches 2 nodes; image pull (small image matters here)
5 t+110s pods Ready, Horizon/queue:work consuming
6 backlog 0 for the cooldown -> scale to 0; Karpenter consolidates the nodesReal scenario: an HPA with minReplicas: 2 and a CPU target of 60% on a Go API; a Laravel queue worker scaled on Redis list length with KEDA; nodes that never scale down because a pod with local storage or a restrictive PDB blocks consolidation.
| Autoscaler | Changes | Signal | Product |
|---|---|---|---|
| HPA | Replica count | Resource, custom, external metrics | Kubernetes built-in |
| VPA | Requests (and limits proportionally) | Observed usage | kubernetes/autoscaler add-on |
| KEDA | Replica count incl. 0 | Queues, streams, cron, Prometheus | CNCF project |
| Cluster Autoscaler | Node group size | Pending pods, idle nodes | kubernetes/autoscaler |
| Karpenter | Individual nodes, instance type | Pending pods, consolidation | AWS-origin, CNCF; v1.x |
Fix / how to use it: HPA manifest for the Go service in Mechanics and for Laravel in Laravel.
Services and EndpointSlices Must-know
In plain words: pods come and go with new IPs; a Service is a stable name and virtual IP that always points at whichever pods with the right labels are ready right now.
Common misunderstanding: "A Service is a load balancer process." For ClusterIP there is no process in the path: kube-proxy (or Cilium's eBPF) writes kernel rules on every node that rewrite the virtual IP to one ready pod IP per connection. Long-lived connections (gRPC, HTTP/2, database pools) therefore stick to one pod and do not rebalance when you scale out.
Definition: a Service selects pods by label; the EndpointSlice controller publishes their addresses with ready, serving and terminating conditions ("no more than 100 endpoints each" by default, configurable up to 1000), and "EndpointSlices act as the source of truth for kube-proxy". Types: ClusterIP (default, internal virtual IP), NodePort (a port from 30000-32767 on every node), LoadBalancer (asks the cloud-controller-manager or a controller such as MetalLB or the AWS Load Balancer Controller for an external L4 load balancer), ExternalName (a DNS CNAME, no proxying), and headless (clusterIP: None: DNS returns the pod IPs directly; used by StatefulSets and client-side balancing). kube-proxy modes: iptables (the default in 1.37), nftables (the future default), ipvs (deprecated since v1.35, disabled by default from v1.40) and kernelspace on Windows. sessionAffinity: ClientIP, internalTrafficPolicy and externalTrafficPolicy: Local (keeps the client source IP, skips the second hop) are the main knobs. Packet-level detail is in Kubernetes Networking.
A pod becomes ready, then terminates
1 readiness passes -> EndpointSlice: 10.0.1.12 ready=true
2 kube-proxy on every node adds a DNAT rule for 10.96.40.10:80 -> 10.0.1.12:8080
3 pod deleted -> endpoint ready=false, terminating=true
4 kube-proxy removes it from new-connection rules; existing conntrack entries stay until closedReal scenario: a gRPC client with one HTTP/2 connection sends all traffic to the first pod after a scale-out; fix with a headless Service plus client-side balancing, or a mesh/L7 proxy (see Service Mesh); externalTrafficPolicy: Local on a LoadBalancer drops traffic to nodes without a local pod unless the cloud LB health-checks healthCheckNodePort; an ExternalName Service points db at an RDS hostname so the app config is the same in every environment.
| Type | Reachable from | Implemented by | Use |
|---|---|---|---|
| ClusterIP | Inside the cluster | kube-proxy / eBPF | Service-to-service |
| Headless | Inside, per-pod DNS | CoreDNS only | StatefulSets, client-side LB |
| NodePort | Node IP:30000-32767 | kube-proxy | Behind an external LB, labs |
| LoadBalancer | Internet or VPC | Cloud controller, AWS Load Balancer Controller, MetalLB | Ingress controller entry, TCP services |
| ExternalName | Inside (DNS CNAME) | CoreDNS | Alias an external host |
Fix / how to use it:
apiVersion: v1
kind: Service
metadata: { name: web, namespace: shop }
spec:
type: ClusterIP
selector: { app: web }
ports: [{ name: http, port: 80, targetPort: http }]Ingress, Ingress controllers and Gateway API Must-know
In plain words: an Ingress or a Gateway API route is a set of HTTP rules ("shop.example.com/api goes to Service api"); an Ingress controller or Gateway implementation is the actual proxy (NGINX, Traefik, HAProxy, Envoy) that reads those rules and does the routing and TLS.
Common misunderstanding: "Creating an Ingress object exposes my app." Without a controller installed and an ingressClassName it serves, nothing happens. And since Ingress NGINX is retired (best-effort maintenance ended in March 2026), new clusters should not start on it.
Definition: Ingress provides "load balancing, SSL termination and name-based virtual hosting"; it is GA but frozen, and "The Kubernetes project recommends using Gateway instead of Ingress". Controller-specific behaviour lives in annotations, which is why Ingress manifests are not portable. Gateway API is a role-oriented family of resources: GatewayClass (the implementation, owned by the platform), Gateway (listeners, ports, TLS; owned by cluster operators), HTTPRoute / GRPCRoute (routes, owned by app teams), with weighted backends, header matching, redirects and cross-namespace ReferenceGrant. Implementations include Envoy Gateway, Istio, Cilium, NGINX Gateway Fabric, Traefik, HAProxy, Kong and the cloud gateways (GKE Gateway, AWS Gateway API Controller).
Request path (north-south)
1 client -> DNS shop.example.com -> cloud LB (Service type LoadBalancer of the gateway)
2 gateway pod (Envoy): TLS terminated, HTTPRoute host/path match, 90/10 weights
3 -> Service web-v1 or web-v2 (ClusterIP) or straight to endpoint IPs (most controllers)
4 -> ready pod; response back the same wayReal scenario: migrating from Ingress NGINX annotations (nginx.ingress.kubernetes.io/rewrite-target, rate limiting) to Gateway API filters or a maintained controller; a canary split of 10% by HTTPRoute weights driven by Argo Rollouts; TLS certificates issued by cert-manager into Secrets referenced by the Gateway listener (TLS details in TLS in Practice).
| Option | API | Strength | Note |
|---|---|---|---|
| Ingress NGINX | Ingress | Was the default for years | Retired after March 2026: migrate |
| Traefik | Ingress, Gateway API, CRDs | Dynamic config, middlewares | Popular on k3s |
| HAProxy Kubernetes Ingress Controller | Ingress, CRDs | Performance, fine L4/L7 tuning | Enterprise edition available |
| Envoy Gateway / Istio | Gateway API | Full Gateway API, mesh integration | Envoy proxy underneath |
| Cloud (AWS Load Balancer Controller, GKE Gateway) | Ingress / Gateway API | Managed L7 LB, no in-cluster proxy | Cloud-specific features |
Fix / how to use it:
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata: { name: web, namespace: shop }
spec:
parentRefs: [{ name: public, namespace: gateway-system }]
hostnames: [shop.example.com]
rules:
- matches: [{ path: { type: PathPrefix, value: / } }]
backendRefs:
- { name: web-stable, port: 80, weight: 90 }
- { name: web-canary, port: 80, weight: 10 }The gateway itself, API gateways and BFFs as an architecture choice are in API Gateway, BFF & Service Mesh.
NetworkPolicy Important
In plain words: by default every pod can talk to every other pod in the cluster; a NetworkPolicy is a firewall rule written with labels that says who may talk to whom.
Common misunderstanding: "I applied a NetworkPolicy, so traffic is restricted." Policies are enforced by the CNI plugin; on a CNI without policy support (plain flannel) they are silently ignored. And a policy only restricts the pods it selects, in the directions it lists.
Definition: a policy selects pods (podSelector) and lists allowed ingress and/or egress peers by podSelector, namespaceSelector or ipBlock, plus ports. Once a pod is selected by any policy for a direction, everything not allowed in that direction is denied. Enforced by Calico, Cilium, Antrea, AWS VPC CNI network policy, GKE Dataplane V2. Remember to allow DNS egress to CoreDNS (UDP/TCP 53) when you default-deny egress.
1 apply default-deny (podSelector: {}) in namespace shop -> all traffic to shop pods blocked
2 allow ingress-system -> web:8000
3 allow web -> postgres:5432, web -> kube-dns:53
4 a compromised web pod cannot reach payments or the cloud metadata IP 169.254.169.254Real scenario: blocking pods from the instance metadata endpoint to stop credential theft; PCI scope reduction by isolating a payments namespace (see DDoS, Firewalls, VPCs & Segmentation); a default-deny that breaks everything because DNS was forgotten.
| Policy | Selects | Allows |
|---|---|---|
| default-deny-all | every pod in namespace | nothing (ingress and egress) |
| allow-from-gateway | app: web | from namespace gateway-system on 8000 |
| allow-db | app: postgres | from app: web on 5432 |
| allow-dns | every pod | egress to kube-dns on 53 |
Fix / how to use it:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: web-ingress, namespace: shop }
spec:
podSelector: { matchLabels: { app: web } }
policyTypes: [Ingress]
ingress:
- from:
- namespaceSelector: { matchLabels: { kubernetes.io/metadata.name: gateway-system } }
ports: [{ port: 8000, protocol: TCP }]Storage: PV, PVC, StorageClass, CSI Important
In plain words: a PersistentVolumeClaim is a pod's request for a disk ("10 GiB, fast, one writer"); a StorageClass says how to create such disks; a CSI driver is the plugin that actually talks to EBS, Persistent Disk, Ceph or NFS.
Common misunderstanding: "Volumes make any app stateful-safe." A block volume (EBS, GCE PD) is attached to one node in one zone; a pod rescheduled to another zone cannot follow its disk, and ReadWriteOnce means one node, not one pod.
Definition: PersistentVolume (PV) is the disk object; PVC is the claim bound to it; dynamic provisioning creates PVs from a StorageClass (provisioner, parameters, reclaimPolicy Delete or Retain, volumeBindingMode: WaitForFirstConsumer so the disk is created in the zone where the pod is scheduled, allowVolumeExpansion). Access modes: ReadWriteOnce, ReadOnlyMany, ReadWriteMany, ReadWriteOncePod. The Container Storage Interface (CSI) moved drivers out of the Kubernetes tree; snapshots use VolumeSnapshot. emptyDir is scratch space that dies with the pod.
1 PVC data-db-0 (gp3, 50Gi, RWO) Pending: WaitForFirstConsumer
2 scheduler places db-0 in zone b -> CSI CreateVolume in zone b -> PV bound
3 node in zone b dies -> db-0 can only run in zone b (volume node affinity)
4 no capacity in b -> db-0 Pending until a node appears thereReal scenario: Laravel storage/app on a RWO volume blocks scaling past one replica; move uploads to S3 (FILESYSTEM_DISK=s3) instead (see Object Storage); a Delete reclaim policy destroys a database disk when someone deletes the namespace.
| Access mode | Meaning | Typical backends |
|---|---|---|
| ReadWriteOnce | Read-write by one node | EBS, GCE PD, Azure Disk |
| ReadOnlyMany | Read-only by many nodes | NFS, snapshots, CephFS |
| ReadWriteMany | Read-write by many nodes | EFS, Filestore, CephFS, NFS |
| ReadWriteOncePod | Read-write by one pod | CSI drivers that support it |
Fix / how to use it: keep web and worker pods stateless (Redis for sessions and cache, S3 for files, managed PostgreSQL), use WaitForFirstConsumer and Retain for anything precious, and back up with snapshots plus application-level backups (Backup & PITR).
Deployment strategies, GitOps, Helm and Kustomize Important
In plain words: rolling replaces pods gradually; blue/green runs the new version next to the old and flips traffic at once; canary sends a small share of traffic to the new version and widens it while metrics look good. GitOps means the cluster pulls its desired state from Git. Helm and Kustomize are two ways to produce the YAML.
Common misunderstanding: "Canary is just replicas: 1 of the new version next to 9 old." That gives roughly 10% only if traffic is spread by pod count and you cannot measure or roll back automatically; real canaries shift traffic by weight at the ingress, gateway or mesh and gate each step on metrics.
Definition: Argo Rollouts is "a Kubernetes controller and set of CRDs which provide advanced deployment capabilities such as blue-green, canary, canary analysis, experimentation, and progressive delivery"; its Rollout replaces the Deployment and uses AnalysisTemplates (Prometheus queries) to promote or abort. Flagger "automates the release process", driving a mesh or ingress and metrics. Argo CD "is a declarative, GitOps continuous delivery tool for Kubernetes"; Flux keeps clusters "in sync with sources of configuration (like Git repositories)". Helm packages charts ("a collection of files that describe a related set of Kubernetes resources") with Go templates and values, and tracks releases; Kustomize customises plain YAML "in a template free way" with bases, overlays and patches (kubectl apply -k).
Canary with Argo Rollouts and Gateway API weights
1 setWeight 10 -> HTTPRoute 90/10
2 analysis: error rate < 1%, p99 < 300 ms for 5 min (Prometheus)
3 setWeight 50 -> analysis again
4 setWeight 100 -> old ReplicaSet scaled down after scaleDownDelaySeconds
analysis fails at step 2 -> abort: weight back to 0, canary scaled down, no human neededReal scenario: a payments API uses blue/green so the switch is atomic and a schema-compatible rollback is one flip; a team with 40 microservices uses one Helm chart for all and per-service values; staging and production overlays in Kustomize differ only in replicas, resources and hostnames; Argo CD reverts a manual kubectl edit (self-heal).
| Strategy | Mechanism | Rollback | Cost |
|---|---|---|---|
| Rolling | Deployment RollingUpdate | kubectl rollout undo (minutes) | None extra |
| Recreate | Stop all then start | Redeploy | Downtime |
| Blue/green | Two ReplicaSets, switch Service selector or route | Instant flip | Double capacity during switch |
| Canary | Weighted traffic + analysis (Argo Rollouts, Flagger) | Automatic abort | Metrics and traffic-shaping layer |
| GitOps | Argo CD / Flux reconcile from Git | git revert | A controller and repo discipline |
Fix / how to use it: the expand/contract rule for database changes still applies to every strategy (Zero-Downtime Schema Migrations); a Helm template fragment:
# templates/deployment.yaml (Helm)
spec:
template:
metadata:
annotations:
checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
spec:
containers:
- name: {{ .Chart.Name }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"Observability hooks: metrics-server, kube-state-metrics, events Good to know
In plain words: metrics-server gives the autoscalers live CPU and memory; kube-state-metrics turns object state (replicas wanted vs available, restarts, pod phases) into Prometheus metrics; Events are the short-lived log of what controllers and the kubelet did.
Common misunderstanding: "metrics-server is my monitoring." Its README: "Metrics Server is meant only for autoscaling purposes", not for monitoring; use Prometheus scraping the kubelet/cAdvisor and kube-state-metrics.
Definition: metrics-server serves the metrics.k8s.io API used by kubectl top and the HPA/VPA. kube-state-metrics "listens to the Kubernetes API server and generates metrics about the state of the objects" (kube_deployment_status_replicas_available, kube_pod_container_status_restarts_total, kube_pod_status_phase). Events (kubectl get events --sort-by=.lastTimestamp) are kept for one hour by default and should be exported if you want history.
1 alert: kube_deployment_status_replicas_available < kube_deployment_spec_replicas for 10m
2 alert: increase(kube_pod_container_status_restarts_total[15m]) > 3
3 kubectl describe deploy/web -> Events: ScalingReplicaSet, ProgressDeadlineExceededReal scenario: a dashboard built on kube-state-metrics shows a rollout stuck at 8/10 available; an HPA shows <unknown>/60% because metrics-server is not installed or pods have no CPU request.
| Signal | Source | Use |
|---|---|---|
| CPU/memory now | metrics-server | HPA, VPA, kubectl top |
| Container usage history | kubelet / cAdvisor via Prometheus | Right-sizing, alerts |
| Object state | kube-state-metrics | Rollout and restart alerts |
| What happened | Events | Debugging, export to logs |
| App metrics and traces | Your app, OpenTelemetry | SLOs (Observability) |
Fix / how to use it: install all three; alert on symptoms and on stuck rollouts, as in Alerting That Actually Works.
Security basics: RBAC, ServiceAccounts, workload identity, Pod Security, seccomp, encryption at rest Must-know
In plain words: decide who may call the API and do what (RBAC), give each workload its own identity (ServiceAccount, mapped to a cloud role with IRSA or Workload Identity instead of static keys), forbid dangerous pod settings at admission (Pod Security Standards), limit system calls (seccomp), and encrypt Secrets in etcd.
Common misunderstanding: "Namespaces are a security boundary." They scope names, RBAC and quotas; without NetworkPolicy, Pod Security and least-privilege RBAC, a pod in one namespace can still reach and sometimes control others.
Definition: RBAC uses Role/ClusterRole (verbs on resources) bound by RoleBinding/ClusterRoleBinding to users, groups or ServiceAccounts. A ServiceAccount token is projected into pods (short-lived, audience-bound since 1.22); set automountServiceAccountToken: false where the pod never calls the API. IRSA (IAM roles for service accounts, Amazon EKS; EKS Pod Identity is the newer option) and Workload Identity Federation for GKE map a ServiceAccount to a cloud IAM role through OIDC. Pod Security Standards define privileged, baseline and restricted profiles, enforced per namespace with labels such as pod-security.kubernetes.io/enforce: restricted (also audit, warn); restricted requires non-root, no privilege escalation, dropped capabilities and a seccomp profile. seccomp RuntimeDefault blocks rarely needed syscalls. Encryption at rest for Secrets is configured on the API server with an EncryptionConfiguration (providers kms v2 recommended, aescbc, aesgcm, secretbox, identity = none); managed clusters offer KMS envelope encryption.
A restricted pod being admitted
1 namespace label pod-security.kubernetes.io/enforce=restricted
2 pod runs as root -> admission rejects: 'violates PodSecurity "restricted:latest": runAsNonRoot != true'
3 fixed securityContext -> admitted; token projected for ServiceAccount web (no RBAC rights)
4 AWS SDK in the pod exchanges the projected token for the IAM role (IRSA) -> S3 access, no static keysReal scenario: a CI deploy ServiceAccount with cluster-admin leaks and an attacker owns the cluster; scope it to patch on Deployments in one namespace. A Laravel pod reads S3 with IRSA instead of AWS_ACCESS_KEY_ID in a Secret. Authorization models in general are in Authorization Models.
| Control | Object / setting | Default | Recommended |
|---|---|---|---|
| API authorization | Role, RoleBinding | No rights for app ServiceAccounts | Least privilege; no cluster-admin for CI |
| Workload identity | ServiceAccount + IRSA / GKE Workload Identity | default ServiceAccount | One ServiceAccount per app |
| Token mount | automountServiceAccountToken | true | false unless the pod calls the API |
| Pod hardening | Pod Security Admission labels | privileged (no enforcement) | restricted for app namespaces |
| Syscalls | seccompProfile: RuntimeDefault | Unconfined unless kubelet default set | RuntimeDefault |
| Secrets at rest | EncryptionConfiguration | identity (plain) on self-managed | kms v2 |
| Image policy | Admission (Kyverno, policy-controller) | Anything | Signed digests from your registry |
Fix / how to use it:
securityContext: # pod level
runAsNonRoot: true
runAsUser: 10001
fsGroup: 10001
seccompProfile: { type: RuntimeDefault }
containers:
- name: web
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities: { drop: [ALL] }
volumeMounts: [{ name: tmp, mountPath: /tmp }]
volumes: [{ name: tmp, emptyDir: {} }]When not to use Kubernetes Important
In plain words: Kubernetes is a platform for building platforms; if you have one or two services and no one whose job is to run the cluster, a managed container service is usually cheaper and safer.
Common misunderstanding: "Kubernetes is the default for containers." Amazon ECS, Google Cloud Run, Azure Container Apps and Fly.io run the same OCI images with far fewer moving parts; Cloud Run "is a fully managed application platform for running your code, function, or container".
Definition: the cost of Kubernetes is the control plane plus everything you add to make it production-ready: CNI, ingress or gateway, cert-manager, external-dns, metrics, logging, autoscalers, policy, secrets operator, backup, and three minor upgrades a year (each release is supported for roughly a year; 1.37's end of life is listed as 2027-10-28). The benefit is a uniform API, portability and a huge ecosystem.
The same Laravel app, two platforms
1 Cloud Run: gcloud run deploy --image ... ; scale to zero, HTTPS, revisions, traffic splitting built in
2 Kubernetes: cluster + node pools + gateway + cert-manager + HPA + KEDA + PDB + NetworkPolicy + GitOps
-> worth it when you run many services, need custom controllers, or need portability across cloudsReal scenario: a startup with one Laravel monolith runs on Laravel Cloud, Forge or ECS Fargate and spends nothing on cluster upgrades; a company with 60 services and a platform team standardises on EKS with Argo CD; a batch-heavy ML team uses Kubernetes for GPU scheduling.
| Platform | You manage | Good for | Limits |
|---|---|---|---|
| Amazon ECS (Fargate or EC2) | Task definitions, services | AWS-only shops, simple fleets | AWS lock-in, fewer extension points |
| Google Cloud Run | Container + config | HTTP services, scale to zero | Request/instance model, GCP |
| Azure Container Apps | Container + scale rules | KEDA-style scaling without a cluster | Azure |
| Fly.io | Machines, regions | Multi-region small apps | Smaller ecosystem |
| Managed Kubernetes (EKS, GKE, AKS) | Workloads, add-ons, upgrades | Many services, custom controllers | Operational load |
| Self-managed Kubernetes | Everything incl. control plane | Regulated or on-prem | Highest load |
Fix / how to use it: start with a managed container platform; move to managed Kubernetes when the number of services, the need for custom scheduling or multi-cloud portability pays for a platform team. Functions as the other alternative are in Serverless.
Mechanics
Formulas and budgets
| Quantity | Formula | Example |
|---|---|---|
| Rollout ceiling | replicas + ceil(maxSurge% × replicas) | 10 + 3 = 13 pods |
| Rollout floor | replicas − floor(maxUnavailable% × replicas) | 10 − 2 = 8 ready |
| Time before startup probe gives up | failureThreshold × periodSeconds | 60 × 2 s = 120 s |
| Time to restart a wedged container | failureThreshold × periodSeconds (+ timeout) | 3 × 10 s = 30 s |
| Time to leave endpoints after a readiness failure | failureThreshold × periodSeconds | 2 × 5 s = 10 s |
| Shutdown budget | preStop + drain + shutdownTimeout + margin ≤ terminationGracePeriodSeconds | 5 + 0 + 20 + 2 ≤ 30 |
| HPA | ceil(current × metric / target), skip within 10% | 4 × 90 / 60 = 6 |
| Database connections | maxReplicas × pool size per pod (× Octane workers) ≤ DB limit | 20 × 4 × 5 = 400 |
The last row is the one that hurts: an HPA maxReplicas is also a promise about database connections. Check it in PostgreSQL and put a pooler (Connection Pooling) in front when the number does not fit:
-- connections per application and state (set application_name per pod, e.g. web-7d9-abc)
SELECT split_part(application_name, '-', 1) AS app,
state,
count(*) AS connections
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY 1, 2
ORDER BY connections DESC;
-- headroom left before "FATAL: sorry, too many clients already"
SELECT current_setting('max_connections')::int
- count(*) AS free_slots
FROM pg_stat_activity;Go service manifests: probes, shutdown, HPA, PDB
apiVersion: apps/v1
kind: Deployment
metadata: { name: orders, namespace: shop }
spec:
strategy: { rollingUpdate: { maxSurge: 25%, maxUnavailable: 0 } }
selector: { matchLabels: { app: orders } }
template:
metadata: { labels: { app: orders } }
spec:
serviceAccountName: orders
automountServiceAccountToken: false
terminationGracePeriodSeconds: 30
securityContext: { runAsNonRoot: true, seccompProfile: { type: RuntimeDefault } }
containers:
- name: orders
image: registry.example.com/orders:1.8.0
ports: [{ name: http, containerPort: 8080 }]
env:
- { name: DRAIN_DELAY_SECONDS, value: "5" }
- { name: SHUTDOWN_TIMEOUT_SECONDS, value: "20" }
- { name: GRACE_SECONDS, value: "30" }
- name: POD_NAME
valueFrom: { fieldRef: { fieldPath: metadata.name } }
- name: GOMEMLIMIT
valueFrom: { resourceFieldRef: { resource: limits.memory } }
resources:
requests: { cpu: 250m, memory: 128Mi }
limits: { memory: 256Mi }
startupProbe: { httpGet: { path: /startupz, port: http }, periodSeconds: 2, failureThreshold: 30 }
livenessProbe: { httpGet: { path: /livez, port: http }, periodSeconds: 10, timeoutSeconds: 2 }
readinessProbe: { httpGet: { path: /readyz, port: http }, periodSeconds: 5, failureThreshold: 2 }
securityContext: { allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: { drop: [ALL] } }
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: { name: orders, namespace: shop }
spec:
scaleTargetRef: { apiVersion: apps/v1, kind: Deployment, name: orders }
minReplicas: 3
maxReplicas: 20
metrics:
- type: Resource
resource: { name: cpu, target: { type: Utilization, averageUtilization: 60 } }
behavior:
scaleDown: { stabilizationWindowSeconds: 300, policies: [{ type: Percent, value: 50, periodSeconds: 60 }] }
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: { name: orders, namespace: shop }
spec:
maxUnavailable: 1
selector: { matchLabels: { app: orders } }The Go binary drains in-process (DRAIN_DELAY_SECONDS), so no preStop is needed; distroless has no sleep binary for an exec hook anyway (the native preStop: { sleep: { seconds: 5 } } action works without one).
Messages and exit codes you will see
| Text | Where | Meaning | Fix |
|---|---|---|---|
0/6 nodes are available: 3 Insufficient cpu, 3 node(s) had untolerated taint | Pod events (FailedScheduling) | No node fits requests/taints | Lower requests, add nodes, add toleration |
Back-off restarting failed container | Pod events | CrashLoopBackOff | kubectl logs --previous |
Liveness probe failed: HTTP probe failed with statuscode: 500 | Pod events | Restart is coming | Check liveness semantics |
Readiness probe failed: ... connect: connection refused | Pod events | Not listening yet or crashed | Startup probe, port |
OOMKilled, exit code 137 | lastState.terminated | Memory limit hit | Raise limit, fix leak, GOMEMLIMIT |
| exit code 143 | lastState.terminated | Exited on SIGTERM | Normal during shutdown |
ImagePullBackOff, pull access denied, toomanyrequests | Pod status/events | Image name, auth, rate limit | Registry mirror, pull secret |
ProgressDeadlineExceeded | Deployment condition | Rollout stalled | Inspect new pods; rollout undo |
BackoffLimitExceeded | Job condition | Job failed permanently | Fix and rerun |
The node was low on resource: memory | Pod status Evicted | Node-pressure eviction | Requests, limits, node size |
Cannot evict pod as it would violate the pod's disruption budget | kubectl drain | PDB blocks | Wait, or fix the PDB |
violates PodSecurity "restricted:latest" | Admission warning/error | Pod spec too privileged | Harden securityContext |
failed calling webhook | Admission | Webhook down with failurePolicy: Fail | Webhook HA, timeouts |
Go
The module academy/containers-kubernetes uses only the standard library (go 1.24). It contains a "before" service, the three probe endpoints, a SIGTERM drain with a budget check, a QoS classifier, a reconciliation-loop simulation, and the program that prints the lab numbers.
Before
A process that works on a laptop: config baked into the image, a 45-second warm-up without a startup probe, one /health that checks the database and is used for liveness, and ListenAndServe with no timeouts and no SIGTERM handling.
// Command before is a typical first container: it works on a laptop and
// misbehaves under Kubernetes. Nothing here is broken Go; it is bad design
// for a scheduler that starts, probes, moves and stops processes.
package main
import (
"log"
"net/http"
"os"
"time"
)
func main() {
// Configuration baked into the image: a new image per environment.
cfg, err := os.ReadFile("/app/config.production.json")
if err != nil {
log.Fatal(err)
}
_ = cfg
// A slow warm-up (cache fill, migrations, JIT of templates) with no
// startup probe: a liveness probe with default settings kills the
// container before it finishes, and the pod enters CrashLoopBackOff.
time.Sleep(45 * time.Second)
mux := http.NewServeMux()
// One health endpoint for everything, and it checks the database.
// Used as the liveness probe, a database blip restarts every replica.
mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) {
if err := pingDatabase(); err != nil {
http.Error(w, "db down", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
})
mux.HandleFunc("/orders", func(w http.ResponseWriter, _ *http.Request) {
time.Sleep(2 * time.Second) // slow handler
w.Write([]byte("ok"))
})
// No timeouts, no signal handling: SIGTERM kills the process at once,
// in-flight requests get connection resets, and the endpoint was still
// receiving traffic because nothing failed readiness first.
log.Fatal(http.ListenAndServe(":8080", mux))
}
func pingDatabase() error { return nil }After
Probe endpoints with the right semantics. Startup gates the others, liveness watches a worker heartbeat and never a dependency, readiness fails while starting, while draining, or when a local dependency is down.
// Package probes implements the three Kubernetes probe endpoints with the
// semantics the kubelet expects:
//
// /startupz succeeds once warm-up is complete; liveness and readiness
// are not run by the kubelet until it has succeeded.
// /livez fails only when this process is wedged and a restart would
// help. It never checks shared dependencies.
// /readyz fails while starting, while draining, or when a dependency
// this replica cannot serve without is unreachable. Failing
// readiness removes the pod from Service EndpointSlices; it
// does not restart anything.
package probes
import (
"context"
"net/http"
"sync/atomic"
"time"
)
// Checker is a dependency check used by readiness only.
type Checker func(ctx context.Context) error
// Health holds the probe state of one process.
type Health struct {
started atomic.Bool
draining atomic.Bool
beat atomic.Int64 // unix nanos of the last worker-loop heartbeat
// Stall is how old the heartbeat may be before liveness fails.
Stall time.Duration
// Deps are checked by readiness with CheckTimeout each.
Deps map[string]Checker
CheckTimeout time.Duration
// Now is replaceable in tests.
Now func() time.Time
}
// New returns a Health with sane defaults.
func New() *Health {
h := &Health{Stall: 30 * time.Second, CheckTimeout: 300 * time.Millisecond, Deps: map[string]Checker{}, Now: time.Now}
h.Beat()
return h
}
// MarkStarted flips the startup probe to success.
func (h *Health) MarkStarted() { h.started.Store(true) }
// StartDraining makes readiness fail so the pod leaves the EndpointSlices.
func (h *Health) StartDraining() { h.draining.Store(true) }
// Draining reports whether shutdown has begun.
func (h *Health) Draining() bool { return h.draining.Load() }
// Beat records progress of the main work loop (called by that loop).
func (h *Health) Beat() { h.beat.Store(h.Now().UnixNano()) }
// Register adds the three endpoints to mux.
func (h *Health) Register(mux *http.ServeMux) {
mux.HandleFunc("GET /startupz", h.startup)
mux.HandleFunc("GET /livez", h.live)
mux.HandleFunc("GET /readyz", h.ready)
}
func (h *Health) startup(w http.ResponseWriter, _ *http.Request) {
if !h.started.Load() {
http.Error(w, "warming up", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
}
func (h *Health) live(w http.ResponseWriter, _ *http.Request) {
age := h.Now().Sub(time.Unix(0, h.beat.Load()))
if age > h.Stall {
// The worker loop stopped making progress: a restart helps.
http.Error(w, "worker loop stalled for "+age.Round(time.Second).String(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func (h *Health) ready(w http.ResponseWriter, r *http.Request) {
switch {
case !h.started.Load():
http.Error(w, "starting", http.StatusServiceUnavailable)
return
case h.draining.Load():
http.Error(w, "draining", http.StatusServiceUnavailable)
return
}
for name, check := range h.Deps {
ctx, cancel := context.WithTimeout(r.Context(), h.CheckTimeout)
err := check(ctx)
cancel()
if err != nil {
http.Error(w, name+" unavailable", http.StatusServiceUnavailable)
return
}
}
w.WriteHeader(http.StatusOK)
}package probes
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func status(t *testing.T, h *Health, path string) int {
t.Helper()
mux := http.NewServeMux()
h.Register(mux)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
return rec.Code
}
func TestStartupGatesReadiness(t *testing.T) {
h := New()
if got := status(t, h, "/startupz"); got != 503 {
t.Fatalf("startup before warm-up = %d, want 503", got)
}
if got := status(t, h, "/readyz"); got != 503 {
t.Fatalf("ready before warm-up = %d, want 503", got)
}
if got := status(t, h, "/livez"); got != 200 {
t.Fatalf("live while warming = %d, want 200", got)
}
h.MarkStarted()
if got := status(t, h, "/startupz"); got != 200 {
t.Fatalf("startup after warm-up = %d, want 200", got)
}
if got := status(t, h, "/readyz"); got != 200 {
t.Fatalf("ready after warm-up = %d, want 200", got)
}
}
func TestDependencyFailsReadinessNotLiveness(t *testing.T) {
h := New()
h.MarkStarted()
h.Deps["postgres"] = func(context.Context) error { return errors.New("connection refused") }
if got := status(t, h, "/readyz"); got != 503 {
t.Fatalf("ready with db down = %d, want 503", got)
}
if got := status(t, h, "/livez"); got != 200 {
t.Fatalf("live with db down = %d, want 200 (a restart would not fix the db)", got)
}
}
func TestDrainingFailsReadiness(t *testing.T) {
h := New()
h.MarkStarted()
h.StartDraining()
if got := status(t, h, "/readyz"); got != 503 {
t.Fatalf("ready while draining = %d, want 503", got)
}
if got := status(t, h, "/livez"); got != 200 {
t.Fatalf("live while draining = %d, want 200", got)
}
}
func TestStalledLoopFailsLiveness(t *testing.T) {
now := time.Unix(1000, 0)
h := New()
h.Now = func() time.Time { return now }
h.Beat()
h.Stall = 30 * time.Second
now = now.Add(31 * time.Second)
if got := status(t, h, "/livez"); got != 500 {
t.Fatalf("live with stalled loop = %d, want 500", got)
}
h.Beat()
if got := status(t, h, "/livez"); got != 200 {
t.Fatalf("live after beat = %d, want 200", got)
}
}SIGTERM drain that fits the grace period. Config.Check refuses a budget that cannot fit terminationGracePeriodSeconds; Run fails readiness, keeps serving for DrainDelay, then calls Shutdown with a deadline and falls back to Close. The test proves an in-flight request survives SIGTERM.
// Package lifecycle runs an HTTP server the way Kubernetes stops pods.
//
// Pod deletion starts two things at the same time: the kubelet runs the
// preStop hook and then sends SIGTERM, and the control plane removes the
// pod from Service EndpointSlices. kube-proxy, ingress controllers and
// cloud load balancers learn about the removal a little later. Run closes
// that gap: on SIGTERM it fails readiness, keeps serving for DrainDelay,
// then calls Shutdown with ShutdownTimeout. The whole sequence must fit in
// terminationGracePeriodSeconds or the kubelet sends SIGKILL.
package lifecycle
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"time"
)
// Drainer is the part of probes.Health that Run needs.
type Drainer interface{ StartDraining() }
// Config is the shutdown budget of one container.
type Config struct {
// PreStop is how long a preStop hook (for example "sleep 5") runs
// before SIGTERM is delivered. Zero when no hook is configured.
PreStop time.Duration
// DrainDelay keeps serving after SIGTERM while endpoints converge.
DrainDelay time.Duration
// ShutdownTimeout bounds http.Server.Shutdown for in-flight requests.
ShutdownTimeout time.Duration
// Grace is the pod's terminationGracePeriodSeconds.
Grace time.Duration
// Margin is kept free for process exit and log flush.
Margin time.Duration
}
// ErrBudget is returned when the shutdown sequence cannot fit the grace period.
var ErrBudget = errors.New("shutdown budget exceeds terminationGracePeriodSeconds")
// Check validates PreStop + DrainDelay + ShutdownTimeout + Margin <= Grace.
// The grace countdown starts before the preStop hook runs, so the hook's
// time is spent from the same budget.
func (c Config) Check() error {
need := c.PreStop + c.DrainDelay + c.ShutdownTimeout + c.Margin
if need > c.Grace {
return fmt.Errorf("%w: need %s, have %s", ErrBudget, need, c.Grace)
}
return nil
}
// Run serves on ln until ctx is cancelled (SIGTERM), then drains.
// It returns nil after a clean drain.
func Run(ctx context.Context, srv *http.Server, ln net.Listener, d Drainer, c Config) error {
if err := c.Check(); err != nil {
return err
}
errc := make(chan error, 1)
go func() { errc <- srv.Serve(ln) }()
select {
case err := <-errc:
return err // listener failed before any signal
case <-ctx.Done():
}
// 1. Fail readiness: new connections should stop arriving.
d.StartDraining()
// 2. Keep accepting while kube-proxy and load balancers catch up.
time.Sleep(c.DrainDelay)
// 3. Stop accepting, finish in-flight requests, close idle keep-alives.
sctx, cancel := context.WithTimeout(context.Background(), c.ShutdownTimeout)
defer cancel()
if err := srv.Shutdown(sctx); err != nil {
_ = srv.Close() // deadline hit: cut remaining connections
return fmt.Errorf("shutdown: %w", err)
}
if err := <-errc; !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
}package lifecycle
import (
"context"
"errors"
"io"
"net"
"net/http"
"sync/atomic"
"testing"
"time"
)
type flag struct{ on atomic.Bool }
func (f *flag) StartDraining() { f.on.Store(true) }
func TestBudget(t *testing.T) {
ok := Config{PreStop: 5 * time.Second, DrainDelay: 5 * time.Second, ShutdownTimeout: 15 * time.Second, Margin: 2 * time.Second, Grace: 30 * time.Second}
if err := ok.Check(); err != nil {
t.Fatalf("27s in 30s should fit: %v", err)
}
bad := ok
bad.ShutdownTimeout = 25 * time.Second
if err := bad.Check(); !errors.Is(err, ErrBudget) {
t.Fatalf("37s in 30s should not fit, got %v", err)
}
}
func TestInFlightRequestSurvivesSIGTERM(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
started := make(chan struct{})
mux := http.NewServeMux()
mux.HandleFunc("/slow", func(w http.ResponseWriter, _ *http.Request) {
close(started)
time.Sleep(300 * time.Millisecond)
io.WriteString(w, "done")
})
srv := &http.Server{Handler: mux, ReadHeaderTimeout: time.Second}
d := &flag{}
ctx, sigterm := context.WithCancel(context.Background())
runErr := make(chan error, 1)
go func() {
runErr <- Run(ctx, srv, ln, d, Config{DrainDelay: 50 * time.Millisecond, ShutdownTimeout: 2 * time.Second, Grace: 30 * time.Second})
}()
body := make(chan string, 1)
go func() {
resp, err := http.Get("http://" + ln.Addr().String() + "/slow")
if err != nil {
body <- "error: " + err.Error()
return
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
body <- string(b)
}()
<-started
sigterm() // the kubelet sends SIGTERM while /slow is running
if got := <-body; got != "done" {
t.Fatalf("in-flight request = %q, want done", got)
}
if err := <-runErr; err != nil {
t.Fatalf("Run returned %v", err)
}
if !d.on.Load() {
t.Fatal("readiness was not failed before shutdown")
}
}
func TestShutdownDeadline(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
started := make(chan struct{})
release := make(chan struct{})
mux := http.NewServeMux()
mux.HandleFunc("/stuck", func(w http.ResponseWriter, _ *http.Request) {
close(started)
<-release
})
srv := &http.Server{Handler: mux}
ctx, sigterm := context.WithCancel(context.Background())
runErr := make(chan error, 1)
go func() {
runErr <- Run(ctx, srv, ln, &flag{}, Config{ShutdownTimeout: 100 * time.Millisecond, Grace: time.Second})
}()
go func() {
resp, err := http.Get("http://" + ln.Addr().String() + "/stuck")
if err == nil {
resp.Body.Close()
}
}()
<-started
sigterm()
err = <-runErr
close(release)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("want deadline exceeded, got %v", err)
}
}The binary: env configuration (ConfigMap, Secret, Downward API), JSON logs to stdout, signal.NotifyContext, server timeouts.
// Command web is the Kubernetes-ready version of before/main.go:
// configuration from the environment (ConfigMap/Secret), separate startup,
// liveness and readiness endpoints, server timeouts, and a SIGTERM drain
// that fits terminationGracePeriodSeconds.
package main
import (
"context"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"academy/containers-kubernetes/lifecycle"
"academy/containers-kubernetes/probes"
)
func envDuration(key string, def time.Duration) time.Duration {
if v, err := strconv.Atoi(os.Getenv(key)); err == nil {
return time.Duration(v) * time.Second
}
return def
}
func main() {
log := slog.New(slog.NewJSONHandler(os.Stdout, nil)) // stdout: the runtime collects it
// POD_NAME and NODE_NAME come from the Downward API (fieldRef).
log = log.With("pod", os.Getenv("POD_NAME"), "node", os.Getenv("NODE_NAME"))
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
health := probes.New()
health.Deps["postgres"] = func(ctx context.Context) error { return nil } // db.PingContext(ctx) in a real service
mux := http.NewServeMux()
health.Register(mux)
mux.HandleFunc("GET /orders", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"orders":[]}`))
})
// A background loop that liveness watches.
go func() {
t := time.NewTicker(5 * time.Second)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
health.Beat() // do one unit of work, then report progress
}
}
}()
// Warm-up runs behind the startup probe instead of a long initialDelaySeconds.
go func() {
time.Sleep(2 * time.Second) // load caches, compile templates
health.MarkStarted()
log.Info("started")
}()
addr := ":" + envOr("PORT", "8080")
ln, err := net.Listen("tcp", addr)
if err != nil {
log.Error("listen", "err", err)
os.Exit(1)
}
srv := &http.Server{
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
cfg := lifecycle.Config{
PreStop: envDuration("PRESTOP_SECONDS", 0),
DrainDelay: envDuration("DRAIN_DELAY_SECONDS", 5*time.Second),
ShutdownTimeout: envDuration("SHUTDOWN_TIMEOUT_SECONDS", 20*time.Second),
Grace: envDuration("GRACE_SECONDS", 30*time.Second),
Margin: 2 * time.Second,
}
log.Info("serving", "addr", addr)
if err := lifecycle.Run(ctx, srv, ln, health, cfg); err != nil {
log.Error("stopped", "err", err)
os.Exit(1)
}
log.Info("drained cleanly")
}
func envOr(k, def string) string {
if v := os.Getenv(k); v != "" {
return v
}
return def
}A reconciliation loop you can test without a cluster. Reconcile is level-triggered: it reads all pods, applies the maxSurge/maxUnavailable rules and creates or deletes a few pods. The tests check the invariants at every pass, a stalled rollout with a broken image, self-healing after a pod is killed, idempotency and scale-in.
// Package reconcile is a tiny, cluster-free model of the Kubernetes
// controller pattern: observe actual state, compare it with desired state,
// act a little, repeat. Reconcile implements the Deployment rolling-update
// rules (maxSurge, maxUnavailable) over a fake set of pods so the
// invariants can be tested without a cluster.
//
// It is a teaching model, not the kube-controller-manager code: the real
// Deployment controller manages ReplicaSets, and the ReplicaSet controller
// manages pods. The arithmetic is the documented one.
package reconcile
import (
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
)
// Spec is the desired state of a Deployment.
type Spec struct {
Replicas int
Revision int // pod template hash, simplified to a number
MaxSurge string // "25%" or "1"
MaxUnavailable string // "25%" or "0"
}
// Pod is the observed state of one replica.
type Pod struct {
Name string
Revision int
Ready bool
}
// Cluster is the fake API server: the list of pods.
type Cluster struct {
Pods []Pod
nextID int
// Broken revisions never become Ready (bad image, failing probe).
Broken map[int]bool
}
// Action is what one reconcile pass did.
type Action struct {
Created []string
Deleted []string
}
// ErrBothZero mirrors the API validation: maxSurge and maxUnavailable
// cannot both be zero, or the rollout could never make progress.
var ErrBothZero = errors.New("maxSurge and maxUnavailable cannot both be 0")
// Resolve turns an int-or-percent into a pod count. Kubernetes rounds
// maxSurge up and maxUnavailable down.
func Resolve(v string, total int, roundUp bool) (int, error) {
if strings.HasSuffix(v, "%") {
p, err := strconv.Atoi(strings.TrimSuffix(v, "%"))
if err != nil || p < 0 {
return 0, fmt.Errorf("bad percent %q", v)
}
x := float64(p) * float64(total) / 100
if roundUp {
return int(math.Ceil(x)), nil
}
return int(math.Floor(x)), nil
}
n, err := strconv.Atoi(v)
if err != nil || n < 0 {
return 0, fmt.Errorf("bad count %q", v)
}
return n, nil
}
// Bounds returns the most pods that may exist and the fewest that must be Ready.
func Bounds(s Spec) (maxTotal, minReady int, err error) {
surge, err := Resolve(s.MaxSurge, s.Replicas, true)
if err != nil {
return 0, 0, err
}
unavail, err := Resolve(s.MaxUnavailable, s.Replicas, false)
if err != nil {
return 0, 0, err
}
if surge == 0 && unavail == 0 {
return 0, 0, ErrBothZero
}
return s.Replicas + surge, s.Replicas - unavail, nil
}
// Tick simulates the kubelet: pods created in the previous pass pass their
// readiness probe now, unless their revision is broken.
func (c *Cluster) Tick() {
for i := range c.Pods {
if !c.Broken[c.Pods[i].Revision] {
c.Pods[i].Ready = true
}
}
}
// Kill removes a pod as a node failure or an eviction would.
func (c *Cluster) Kill(name string) {
out := c.Pods[:0]
for _, p := range c.Pods {
if p.Name != name {
out = append(out, p)
}
}
c.Pods = out
}
// Counts returns total, ready, current-revision and old-revision pods.
func (c *Cluster) Counts(rev int) (total, ready, current, old int) {
for _, p := range c.Pods {
total++
if p.Ready {
ready++
}
if p.Revision == rev {
current++
} else {
old++
}
}
return
}
// Reconcile performs one pass. It is level-triggered: it reads the whole
// observed state every time, so a missed event or a restart of the
// controller changes nothing.
func Reconcile(s Spec, c *Cluster) (Action, error) {
maxTotal, minReady, err := Bounds(s)
if err != nil {
return Action{}, err
}
var act Action
total, _, current, _ := c.Counts(s.Revision)
// Scale up the current revision, never above replicas + maxSurge.
create := min(maxTotal-total, s.Replicas-current)
for i := 0; i < create; i++ {
c.nextID++
name := fmt.Sprintf("web-r%d-%02d", s.Revision, c.nextID)
c.Pods = append(c.Pods, Pod{Name: name, Revision: s.Revision})
act.Created = append(act.Created, name)
}
// Scale down: old pods first (not-ready ones cost no availability),
// then surplus current pods, never letting Ready drop below minReady.
_, ready, current, _ := c.Counts(s.Revision)
victims := make([]Pod, 0, len(c.Pods))
for _, p := range c.Pods {
if p.Revision != s.Revision {
victims = append(victims, p)
}
}
sort.SliceStable(victims, func(i, j int) bool { return !victims[i].Ready && victims[j].Ready })
if current > s.Replicas { // scale-in of the current revision
extra := current - s.Replicas
for i := len(c.Pods) - 1; i >= 0 && extra > 0; i-- {
if c.Pods[i].Revision == s.Revision {
victims = append(victims, c.Pods[i])
extra--
}
}
}
for _, v := range victims {
if v.Ready && ready-1 < minReady {
continue
}
if v.Revision == s.Revision && current <= s.Replicas {
continue
}
if v.Ready {
ready--
}
if v.Revision == s.Revision {
current--
}
c.Kill(v.Name)
act.Deleted = append(act.Deleted, v.Name)
}
return act, nil
}
// Converged reports whether the observed state equals the desired state.
func Converged(s Spec, c *Cluster) bool {
total, ready, current, old := c.Counts(s.Revision)
return old == 0 && current == s.Replicas && ready == s.Replicas && total == s.Replicas
}
// Seed creates n Ready pods of a revision (the state before a rollout).
func (c *Cluster) Seed(n, rev int) {
for i := 0; i < n; i++ {
c.nextID++
c.Pods = append(c.Pods, Pod{Name: fmt.Sprintf("web-r%d-%02d", rev, c.nextID), Revision: rev, Ready: true})
}
}package reconcile
import (
"errors"
"testing"
)
func TestResolveRounding(t *testing.T) {
surge, _ := Resolve("25%", 10, true)
unavail, _ := Resolve("25%", 10, false)
if surge != 3 || unavail != 2 {
t.Fatalf("25%% of 10: surge=%d unavailable=%d, want 3 and 2", surge, unavail)
}
if _, _, err := Bounds(Spec{Replicas: 3, MaxSurge: "0", MaxUnavailable: "0"}); !errors.Is(err, ErrBothZero) {
t.Fatalf("want ErrBothZero, got %v", err)
}
// 25% of 3 replicas: surge rounds up to 1, unavailable rounds down to 0.
maxTotal, minReady, _ := Bounds(Spec{Replicas: 3, MaxSurge: "25%", MaxUnavailable: "25%"})
if maxTotal != 4 || minReady != 3 {
t.Fatalf("3 replicas at 25%%: maxTotal=%d minReady=%d, want 4 and 3", maxTotal, minReady)
}
}
func TestRollingUpdateInvariants(t *testing.T) {
for _, s := range []Spec{
{Replicas: 10, Revision: 2, MaxSurge: "25%", MaxUnavailable: "25%"},
{Replicas: 4, Revision: 2, MaxSurge: "1", MaxUnavailable: "0"},
{Replicas: 4, Revision: 2, MaxSurge: "0", MaxUnavailable: "1"},
} {
c := &Cluster{}
c.Seed(s.Replicas, 1)
maxTotal, minReady, _ := Bounds(s)
for tick := 0; tick < 50 && !Converged(s, c); tick++ {
if _, err := Reconcile(s, c); err != nil {
t.Fatal(err)
}
total, ready, _, _ := c.Counts(s.Revision)
if total > maxTotal {
t.Fatalf("%+v tick %d: %d pods > maxTotal %d", s, tick, total, maxTotal)
}
if ready < minReady {
t.Fatalf("%+v tick %d: %d ready < minReady %d", s, tick, ready, minReady)
}
c.Tick()
}
if !Converged(s, c) {
t.Fatalf("%+v did not converge: %+v", s, c.Pods)
}
}
}
func TestBrokenRevisionStallsButKeepsCapacity(t *testing.T) {
s := Spec{Replicas: 10, Revision: 2, MaxSurge: "25%", MaxUnavailable: "25%"}
c := &Cluster{Broken: map[int]bool{2: true}}
c.Seed(10, 1)
for tick := 0; tick < 20; tick++ {
if _, err := Reconcile(s, c); err != nil {
t.Fatal(err)
}
c.Tick()
}
total, ready, current, old := c.Counts(2)
// The rollout is stuck (progressDeadlineSeconds would report it), but
// 8 old pods keep serving: never fewer than replicas - maxUnavailable.
if ready != 8 || old != 8 || current != 5 || total != 13 {
t.Fatalf("stalled state total=%d ready=%d current=%d old=%d", total, ready, current, old)
}
}
func TestSelfHealing(t *testing.T) {
s := Spec{Replicas: 3, Revision: 1, MaxSurge: "25%", MaxUnavailable: "25%"}
c := &Cluster{}
c.Seed(3, 1)
c.Kill(c.Pods[0].Name) // a node dies
act, err := Reconcile(s, c)
if err != nil {
t.Fatal(err)
}
if len(act.Created) != 1 {
t.Fatalf("want 1 replacement pod, got %v", act.Created)
}
c.Tick()
if !Converged(s, c) {
t.Fatalf("not healed: %+v", c.Pods)
}
// Idempotent: a second pass with nothing to do does nothing.
if act, _ := Reconcile(s, c); len(act.Created)+len(act.Deleted) != 0 {
t.Fatalf("second pass acted: %+v", act)
}
}
func TestScaleIn(t *testing.T) {
s := Spec{Replicas: 2, Revision: 1, MaxSurge: "1", MaxUnavailable: "0"}
c := &Cluster{}
c.Seed(5, 1)
if _, err := Reconcile(s, c); err != nil {
t.Fatal(err)
}
if !Converged(s, c) {
t.Fatalf("scale-in failed: %+v", c.Pods)
}
}QoS classes, as the API server computes them:
// Package qos reproduces how Kubernetes assigns a Pod QoS class from the
// requests and limits of its containers (CPU and memory only).
//
// Guaranteed: every container has CPU and memory limits, and requests
// equal to the limits (a missing request defaults to the limit).
// BestEffort: no container has any CPU or memory request or limit.
// Burstable: anything else.
package qos
// Class is a Pod QoS class.
type Class string
const (
Guaranteed Class = "Guaranteed"
Burstable Class = "Burstable"
BestEffort Class = "BestEffort"
)
// Resources are quantities in millicores and bytes; zero means "not set".
type Resources struct {
CPUMilli int64
MemBytes int64
}
// Container has requests and limits as written in the Pod spec.
type Container struct {
Name string
Requests Resources
Limits Resources
}
// Of returns the QoS class of a Pod with the given containers.
func Of(cs []Container) Class {
set := false
guaranteed := true
for _, c := range cs {
req := c.Requests
// The API server defaults a missing request to the limit.
if req.CPUMilli == 0 {
req.CPUMilli = c.Limits.CPUMilli
}
if req.MemBytes == 0 {
req.MemBytes = c.Limits.MemBytes
}
if req.CPUMilli != 0 || req.MemBytes != 0 || c.Limits.CPUMilli != 0 || c.Limits.MemBytes != 0 {
set = true
}
if c.Limits.CPUMilli == 0 || c.Limits.MemBytes == 0 ||
req.CPUMilli != c.Limits.CPUMilli || req.MemBytes != c.Limits.MemBytes {
guaranteed = false
}
}
switch {
case !set:
return BestEffort
case guaranteed:
return Guaranteed
default:
return Burstable
}
}
// EvictionRank orders classes for node-pressure eviction: the kubelet looks
// first at pods whose usage exceeds their requests, then priority, then
// usage relative to requests. BestEffort pods have no requests, so they are
// the first candidates; Guaranteed pods within requests are the last.
func EvictionRank(c Class) int {
switch c {
case BestEffort:
return 0
case Burstable:
return 1
default:
return 2
}
}package qos
import "testing"
const mi = 1 << 20
func TestOf(t *testing.T) {
cases := []struct {
name string
cs []Container
want Class
}{
{"nothing set", []Container{{Name: "app"}}, BestEffort},
{"limits only (requests default to limits)", []Container{{Name: "app", Limits: Resources{500, 512 * mi}}}, Guaranteed},
{"requests equal limits", []Container{{Name: "app", Requests: Resources{500, 512 * mi}, Limits: Resources{500, 512 * mi}}}, Guaranteed},
{"memory limit only, no cpu", []Container{{Name: "app", Requests: Resources{250, 256 * mi}, Limits: Resources{0, 512 * mi}}}, Burstable},
{"requests below limits", []Container{{Name: "app", Requests: Resources{250, 256 * mi}, Limits: Resources{1000, 512 * mi}}}, Burstable},
{"one guaranteed, one sidecar without resources", []Container{
{Name: "app", Requests: Resources{500, 512 * mi}, Limits: Resources{500, 512 * mi}},
{Name: "log-shipper"},
}, Burstable},
}
for _, tc := range cases {
if got := Of(tc.cs); got != tc.want {
t.Errorf("%s: got %s, want %s", tc.name, got, tc.want)
}
}
if !(EvictionRank(BestEffort) < EvictionRank(Burstable) && EvictionRank(Burstable) < EvictionRank(Guaranteed)) {
t.Fatal("eviction order must be BestEffort, Burstable, Guaranteed")
}
}The lab program (deterministic):
// Command k8ssim prints the numbers used in the chapter lab: a rolling
// update trace, a stalled rollout, QoS classes, and shutdown budgets.
// It is deterministic and needs no cluster.
package main
import (
"fmt"
"strings"
"time"
"academy/containers-kubernetes/lifecycle"
"academy/containers-kubernetes/qos"
"academy/containers-kubernetes/reconcile"
)
func trace(title string, s reconcile.Spec, broken bool, ticks int) {
c := &reconcile.Cluster{Broken: map[int]bool{}}
if broken {
c.Broken[s.Revision] = true
}
c.Seed(s.Replicas, s.Revision-1)
maxTotal, minReady, _ := reconcile.Bounds(s)
fmt.Printf("%s: replicas=%d maxSurge=%s maxUnavailable=%s -> at most %d pods, at least %d ready\n",
title, s.Replicas, s.MaxSurge, s.MaxUnavailable, maxTotal, minReady)
fmt.Println(" tick created deleted total ready new old")
for t := 0; t < ticks; t++ {
act, _ := reconcile.Reconcile(s, c)
total, ready, cur, old := c.Counts(s.Revision)
fmt.Printf(" %4d %7d %7d %5d %5d %3d %3d\n", t, len(act.Created), len(act.Deleted), total, ready, cur, old)
if reconcile.Converged(s, c) {
fmt.Printf(" converged after %d passes\n", t+1)
return
}
c.Tick()
}
fmt.Println(" not converged: rollout stalled (Deployment condition Progressing=False after progressDeadlineSeconds)")
}
func main() {
trace("1) rolling update", reconcile.Spec{Replicas: 10, Revision: 2, MaxSurge: "25%", MaxUnavailable: "25%"}, false, 20)
trace("2) zero-downtime, one at a time", reconcile.Spec{Replicas: 4, Revision: 2, MaxSurge: "1", MaxUnavailable: "0"}, false, 20)
trace("3) broken image", reconcile.Spec{Replicas: 10, Revision: 2, MaxSurge: "25%", MaxUnavailable: "25%"}, true, 5)
fmt.Println("4) QoS classes")
mi := int64(1 << 20)
for _, p := range []struct {
name string
cs []qos.Container
}{
{"no resources", []qos.Container{{Name: "app"}}},
{"req 250m/256Mi, lim 1/512Mi", []qos.Container{{Name: "app", Requests: qos.Resources{CPUMilli: 250, MemBytes: 256 * mi}, Limits: qos.Resources{CPUMilli: 1000, MemBytes: 512 * mi}}}},
{"req = lim 500m/512Mi", []qos.Container{{Name: "app", Requests: qos.Resources{CPUMilli: 500, MemBytes: 512 * mi}, Limits: qos.Resources{CPUMilli: 500, MemBytes: 512 * mi}}}},
} {
fmt.Printf(" %-30s %s\n", p.name, qos.Of(p.cs))
}
fmt.Println("5) shutdown budgets (grace 30s)")
for _, c := range []lifecycle.Config{
{PreStop: 5 * time.Second, DrainDelay: 0, ShutdownTimeout: 20 * time.Second, Margin: 2 * time.Second, Grace: 30 * time.Second},
{PreStop: 0, DrainDelay: 5 * time.Second, ShutdownTimeout: 20 * time.Second, Margin: 2 * time.Second, Grace: 30 * time.Second},
{PreStop: 10 * time.Second, DrainDelay: 5 * time.Second, ShutdownTimeout: 20 * time.Second, Margin: 2 * time.Second, Grace: 30 * time.Second},
} {
res := "fits"
if err := c.Check(); err != nil {
res = strings.TrimPrefix(err.Error(), lifecycle.ErrBudget.Error()+": ")
res = "SIGKILL risk (" + res + ")"
}
fmt.Printf(" preStop=%-4s drain=%-3s shutdown=%-4s -> %s\n", c.PreStop, c.DrainDelay, c.ShutdownTimeout, res)
}
}The image: multi-stage, static binary, distroless nonroot, exec-form entrypoint.
# syntax=docker/dockerfile:1
# Multi-stage build: compile with the full toolchain, ship only the binary.
# Pin by digest in CI (FROM golang:1.24-bookworm@sha256:...) so a re-pushed
# tag cannot change what you build; let a bot (Renovate, Dependabot) bump it.
ARG GO_VERSION=1.24
FROM golang:${GO_VERSION}-bookworm AS build
WORKDIR /src
# Dependencies first: this layer is cached until go.mod/go.sum change.
COPY go.mod ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .
# Static binary: no libc needed in the runtime image.
RUN --mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/web ./cmd/web
# Distroless static, non-root variant: no shell, no package manager,
# runs as UID 65532. Roughly a few MB plus your binary.
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/web /web
USER 65532:65532
EXPOSE 8080
# Exec form: the binary is PID 1 and receives SIGTERM directly.
ENTRYPOINT ["/web"]The Go angle
| Go feature | Role in Kubernetes | Note |
|---|---|---|
CGO_ENABLED=0 static builds | Runs on distroless/static or scratch | Add CA certs/tzdata if you use scratch |
signal.NotifyContext(ctx, syscall.SIGTERM) | Turns SIGTERM into cancellation | Added in Go 1.16 |
http.Server.Shutdown(ctx) | "first closing all open listeners, then closing all idle connections, and then waiting" for active ones | Always pass a deadline; Close as fallback |
RegisterOnShutdown | Tell hijacked/WebSocket connections to close | Shutdown does not wait for them |
ReadHeaderTimeout and friends | Bound slow clients | Avoid goroutine pile-ups behind the gateway |
GOMEMLIMIT from the Downward API | GC works before the OOM killer | Set a bit below the limit in practice |
GOMAXPROCS | Match the CPU limit | Go 1.25+ is container-aware; older: go.uber.org/automaxprocs |
log/slog to stdout | The kubelet and log agents collect it | No log files inside the container |
k8s.io/client-go, controller-runtime | Real controllers and operators | Informers, work queues, leader election |
gRPC health/grpc_health_v1 | Native grpc probes | GracefulStop() on SIGTERM |
Laravel
Before
One /health route that pings PostgreSQL and Redis, used as liveness; migrations in the entrypoint of every replica.
<?php
// routes/web.php in the "before" image: one health route used for both
// liveness and readiness, and it checks shared dependencies.
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Route;
Route::get('/health', function () {
// As a liveness probe this restarts every pod when PostgreSQL or Redis
// blips: the restart cannot fix the database, and all replicas pay a
// cold start (OPcache, Octane boot) at the same moment.
DB::select('select 1');
Redis::connection()->ping();
// Running migrations from a request or from the container entrypoint
// means N replicas race to migrate on every rollout.
return response()->json(['ok' => true]);
});After
The image: Composer and Node build stages, FrankenPHP runtime with Octane, non-root UID 10001 on unprivileged port 8000, optimize at start, exec so Octane is PID 1.
# syntax=docker/dockerfile:1
# Laravel 13 under Octane + FrankenPHP, multi-stage, non-root.
# Pin every FROM by digest in CI; the tags below are for readability.
# 1) PHP dependencies without dev packages; the lock file decides versions.
FROM composer:2 AS vendor
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install --no-dev --no-scripts --no-autoloader --prefer-dist --no-interaction
COPY . .
RUN composer dump-autoload --optimize --classmap-authoritative --no-dev
# 2) Front-end assets (Vite); node_modules never reach the runtime image.
FROM node:22-bookworm-slim AS assets
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
# 3) Runtime: FrankenPHP (Caddy + PHP in one binary) serving Octane workers.
FROM dunglas/frankenphp:1-php8.4-bookworm AS runtime
RUN install-php-extensions pcntl pdo_pgsql redis opcache intl zip
ENV SERVER_NAME=:8000 \
APP_ENV=production \
LOG_CHANNEL=stderr
WORKDIR /app
COPY --from=vendor /app /app
COPY --from=assets /app/public/build /app/public/build
ARG USER=laravel
RUN useradd --uid 10001 --no-create-home ${USER} \
# unprivileged port 8000: drop the bind capability entirely
&& setcap -r /usr/local/bin/frankenphp \
&& chown -R ${USER}:${USER} /app/storage /app/bootstrap/cache /config/caddy /data/caddy
USER 10001
EXPOSE 8000
# No migrations here: they run once per release as a Kubernetes Job.
# `optimize` caches config/routes/views at start, when the pod env exists;
# `exec` makes Octane PID 1 so it receives SIGTERM from the kubelet.
# --max-requests recycles a worker after N requests to contain leaks.
CMD ["sh", "-c", "php artisan optimize && exec php artisan octane:frankenphp --host=0.0.0.0 --port=8000 --workers=4 --max-requests=500"]Liveness on /up, trusted proxies in bootstrap/app.php. The framework docs: the /up route "will return a 200 HTTP response if the application has booted without exceptions", and may be used by "an orchestration system such as Kubernetes".
<?php
// bootstrap/app.php (Laravel 13): /up is the liveness endpoint, the
// ingress controller is a trusted proxy, nothing else changes.
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
// 200 if the app boots, 500 otherwise. No dependency checks here.
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
// Requests arrive through the ingress controller / Gateway inside
// the pod network; trust it so URLs and client IPs are right.
$middleware->trustProxies(at: ['10.0.0.0/8']);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();Readiness separate from liveness, and a preStop command that makes it fail before SIGTERM:
<?php
namespace App\Http\Controllers;
use App\Console\Commands\PrepareShutdown;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Throwable;
/**
* Readiness: "may this pod receive traffic right now?"
* Fails while draining (flag written by the preStop hook, visible to every
* Octane worker in the pod) or when a dependency this pod cannot serve
* without is unreachable. Kubernetes reacts by removing the pod from the
* Service EndpointSlices; nothing is restarted.
*/
class ReadinessController
{
public function __invoke(): JsonResponse
{
if (file_exists(PrepareShutdown::flagPath())) {
return response()->json(['ready' => false, 'reason' => 'draining'], 503);
}
$checks = [];
try {
DB::select('select 1');
$checks['database'] = 'ok';
} catch (Throwable) {
$checks['database'] = 'down';
}
try {
Redis::connection()->ping();
$checks['redis'] = 'ok';
} catch (Throwable) {
$checks['redis'] = 'down';
}
$ready = ! in_array('down', $checks, true);
return response()->json(['ready' => $ready, 'checks' => $checks], $ready ? 200 : 503);
}
}<?php
namespace App\Console\Commands;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
/**
* Run as the container preStop hook:
* lifecycle.preStop.exec.command: ["php", "artisan", "app:prepare-shutdown", "--wait=5"]
* It makes readiness fail, then waits while EndpointSlices, kube-proxy and
* the ingress controller stop sending new requests. The kubelet sends
* SIGTERM to the server only after this hook returns, and the wait is
* spent from terminationGracePeriodSeconds.
*/
#[Signature('app:prepare-shutdown {--wait=5 : Seconds to keep serving after failing readiness}')]
#[Description('Fail readiness and wait for endpoints to converge before SIGTERM')]
class PrepareShutdown extends Command
{
public static function flagPath(): string
{
// /tmp is an emptyDir shared by all workers of this pod; the root
// filesystem can stay read-only.
return sys_get_temp_dir().'/app-draining';
}
public function handle(): int
{
file_put_contents(self::flagPath(), (string) time());
$wait = max(0, (int) $this->option('wait'));
$this->info("readiness failing; waiting {$wait}s for endpoints to converge");
sleep($wait);
return self::SUCCESS;
}
}<?php
use App\Http\Controllers\ReadinessController;
use Illuminate\Support\Facades\Route;
// Liveness is the framework's /up route (bootstrap/app.php).
// Readiness is separate and may check dependencies.
Route::get('/ready', ReadinessController::class);The schedule runs in exactly one place:
<?php
use Illuminate\Support\Facades\Schedule;
// routes/console.php: the schedule runs in ONE place. In Kubernetes either a
// single-replica Deployment running `php artisan schedule:work`, or a
// CronJob running `php artisan schedule:run` every minute. onOneServer()
// needs a shared cache (Redis) and protects you if both ever run at once.
Schedule::command('reports:daily')
->dailyAt('02:00')
->onOneServer()
->withoutOverlapping();
Schedule::command('horizon:snapshot')->everyFiveMinutes();
Schedule::command('queue:prune-failed --hours=168')->daily()->onOneServer();Manifests: web Deployment (Octane), migration Job per release, Horizon Deployment, scheduler, HPA.
apiVersion: apps/v1
kind: Deployment
metadata: { name: shop-web, namespace: shop }
spec:
strategy: { rollingUpdate: { maxSurge: 25%, maxUnavailable: 0 } }
selector: { matchLabels: { app: shop-web } }
template:
metadata: { labels: { app: shop-web } }
spec:
serviceAccountName: shop # IRSA / Workload Identity for S3
terminationGracePeriodSeconds: 30
containers:
- name: web
image: registry.example.com/shop:2026.11.3
ports: [{ name: http, containerPort: 8000 }]
envFrom:
- configMapRef: { name: shop-config } # APP_ENV, CACHE_STORE=redis, SESSION_DRIVER=redis, FILESYSTEM_DISK=s3
- secretRef: { name: shop-secrets } # APP_KEY, DB_PASSWORD, REDIS_PASSWORD
resources:
requests: { cpu: "1", memory: 512Mi }
limits: { memory: 1Gi }
startupProbe: { httpGet: { path: /up, port: http }, periodSeconds: 2, failureThreshold: 45 }
livenessProbe: { httpGet: { path: /up, port: http }, periodSeconds: 10, timeoutSeconds: 2 }
readinessProbe: { httpGet: { path: /ready, port: http }, periodSeconds: 5, failureThreshold: 2 }
lifecycle:
preStop: { exec: { command: ["php", "artisan", "app:prepare-shutdown", "--wait=5"] } }
volumeMounts: [{ name: tmp, mountPath: /tmp }]
volumes: [{ name: tmp, emptyDir: {} }]
---
apiVersion: batch/v1
kind: Job
metadata: { name: shop-migrate-2026-11-3, namespace: shop }
spec:
backoffLimit: 2
activeDeadlineSeconds: 600
ttlSecondsAfterFinished: 86400
template:
spec:
restartPolicy: Never
containers:
- name: migrate
image: registry.example.com/shop:2026.11.3
command: ["php", "artisan", "migrate", "--force", "--isolated"]
envFrom: [{ secretRef: { name: shop-secrets } }, { configMapRef: { name: shop-config } }]
---
apiVersion: apps/v1
kind: Deployment
metadata: { name: shop-horizon, namespace: shop }
spec:
replicas: 2
selector: { matchLabels: { app: shop-horizon } }
template:
metadata: { labels: { app: shop-horizon } }
spec:
terminationGracePeriodSeconds: 330 # longest job timeout (300 s) + margin
containers:
- name: horizon
image: registry.example.com/shop:2026.11.3
command: ["php", "artisan", "horizon"]
lifecycle:
preStop: { exec: { command: ["php", "artisan", "horizon:terminate"] } }
envFrom: [{ secretRef: { name: shop-secrets } }, { configMapRef: { name: shop-config } }]
---
# Scheduler option A: one long-running pod
apiVersion: apps/v1
kind: Deployment
metadata: { name: shop-scheduler, namespace: shop }
spec:
replicas: 1
strategy: { type: Recreate } # never two schedulers during a rollout
selector: { matchLabels: { app: shop-scheduler } }
template:
metadata: { labels: { app: shop-scheduler } }
spec:
containers:
- name: scheduler
image: registry.example.com/shop:2026.11.3
command: ["php", "artisan", "schedule:work"]
envFrom: [{ secretRef: { name: shop-secrets } }, { configMapRef: { name: shop-config } }]
---
# Scheduler option B: a CronJob that runs schedule:run every minute
apiVersion: batch/v1
kind: CronJob
metadata: { name: shop-schedule-run, namespace: shop }
spec:
schedule: "* * * * *"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 1
jobTemplate:
spec:
ttlSecondsAfterFinished: 600
template:
spec:
restartPolicy: Never
containers:
- name: schedule
image: registry.example.com/shop:2026.11.3
command: ["php", "artisan", "schedule:run"]
envFrom: [{ secretRef: { name: shop-secrets } }, { configMapRef: { name: shop-config } }]
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: { name: shop-web, namespace: shop }
spec:
scaleTargetRef: { apiVersion: apps/v1, kind: Deployment, name: shop-web }
minReplicas: 3
maxReplicas: 20 # x 4 Octane workers x DB pool: check max_connections
metrics:
- type: Resource
resource: { name: cpu, target: { type: Utilization, averageUtilization: 65 } }A minute-level CronJob creates 1,440 pods a day; option A is lighter, option B needs no long-running pod. With either, onOneServer() protects you if two ever overlap. Queue workers scaled by KEDA instead of Horizon are in Competing Consumers and Laravel Queue Internals.
The Laravel angle
| Laravel feature | Role in Kubernetes | Note |
|---|---|---|
health: '/up' + DiagnosingHealth event | Liveness endpoint | Keep listeners cheap; do not add DB checks for liveness |
Octane (octane:frankenphp, --workers, --max-requests) | One long-lived app server per pod | Servers: FrankenPHP, Open Swoole, Swoole, RoadRunner |
| php-fpm + NGINX | Two containers in one pod (or one image with a supervisor) | Classic; readiness on NGINX, fpm pm.max_children sizing |
octane:reload | Reload workers on one host | In Kubernetes prefer a new rollout |
php artisan optimize | Cache config/routes/views at start | After caching, env() outside config returns null |
migrate --force --isolated | One migration per release (Job) | --isolated takes a cache lock |
Horizon + horizon:terminate | Worker Deployment, graceful stop | Grace period ≥ job timeout |
schedule:work / schedule:run + onOneServer() | Scheduler as a single pod or CronJob | Needs a shared cache store |
SESSION_DRIVER=redis, CACHE_STORE=redis | Stateless pods | file stores break with replicas |
FILESYSTEM_DISK=s3 | No PVC for uploads | league/flysystem-aws-s3-v3; IRSA for credentials |
trustProxies(at: ...) | Correct scheme and client IP behind the gateway | Use the pod/LB CIDR, not *, when you can |
LOG_CHANNEL=stderr | Logs collected by the node agent | No storage/logs on an ephemeral disk |
Solving the classic problems
502s during every deploy
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Readiness + drain delay | Fail readiness on SIGTERM, keep serving 5 s, then Shutdown | Removes the endpoint race | 5 s longer rollouts |
preStop sleep | preStop: { sleep: { seconds: 5 } } | No app change | Spends grace budget |
maxUnavailable: 0 | Surge only | No capacity dip | Needs spare capacity |
| Exec-form entrypoint | App is PID 1 | Receives SIGTERM | Rebuild image |
Pods restart when the database blips
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Split endpoints | /livez local, /readyz with deps | No restart storm | Two endpoints |
| Startup probe | Gate liveness until warm | No kill during boot | One more probe |
| Higher liveness timeout | timeoutSeconds: 2-5 | Survive GC pauses | Slower detection |
A rollout is stuck and nobody noticed
| Solution | How | Advantage | Cost |
|---|---|---|---|
Alert on ProgressDeadlineExceeded | kube-state-metrics condition | Detects in 10 min | An alert rule |
kubectl rollout status --timeout in CI | Fail the pipeline | Fast feedback | Pipeline waits |
| Argo Rollouts analysis | Automatic abort | No human | Controller + metrics |
Nodes cannot be drained
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Sane PDBs | maxUnavailable: 1, ≥ 2 replicas | Drains progress | More replicas |
unhealthyPodEvictionPolicy: AlwaysAllow | Broken pods can go | Upgrades not blocked by bugs | None |
| Avoid local storage | S3/Redis instead of emptyDir data | Consolidation possible | Remote I/O |
Pods OOM-killed or throttled under load
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Measure, then size | VPA Off recommendations, Prometheus | Real numbers | Time |
| No CPU limit, memory limit above peak | Burstable with headroom | No throttling | Noisy neighbours |
GOMEMLIMIT / Octane --max-requests | Runtime-level memory control | Fewer OOM kills | Tuning |
Scaling out overloads the database
| Solution | How | Advantage | Cost |
|---|---|---|---|
Cap maxReplicas by connection math | See formulas | Predictable | Lower peak |
| PgBouncer / RDS Proxy | Pool across pods | Many pods, few connections | One more hop |
| Scale on the right metric | Latency/queue via KEDA or custom metrics | Scale when it helps | Metrics pipeline |
Choosing
Which workload object
| Workload | Object | Extra | Reason |
|---|---|---|---|
| Stateless HTTP/gRPC API | Deployment + HPA + PDB | Probes, spread, drain | Interchangeable replicas |
| Queue workers | Deployment + KEDA (or Horizon) | Long grace, idempotent jobs | Scale on backlog |
| Database, broker, quorum system | Operator managing a StatefulSet, or managed service | Backups, anti-affinity | Identity and disks |
| Node agent | DaemonSet | Tolerations, small requests | One per node |
| Migration, backfill | Job | backoffLimit, ttlSecondsAfterFinished | Run once |
| Periodic task | CronJob or single scheduler pod | concurrencyPolicy: Forbid, onOneServer() | No duplicates |
Which release strategy
| Situation | Strategy | Tool |
|---|---|---|
| Most services | Rolling, maxUnavailable: 0 | Deployment |
| Risky change, good metrics | Canary with analysis | Argo Rollouts, Flagger |
| Need instant switch and rollback | Blue/green | Argo Rollouts, two Deployments + route |
| Incompatible versions cannot coexist | Recreate (accept downtime) | Deployment |
Which platform
| Team and system | Platform | Reason |
|---|---|---|
| 1–3 services, no platform team | Cloud Run, ECS Fargate, Azure Container Apps, Fly.io | No cluster to run |
| Laravel monolith | Laravel Cloud/Forge, ECS, or Cloud Run | Simple deploys |
| 10+ services, shared tooling | Managed Kubernetes (EKS, GKE, AKS) | Uniform API, ecosystem |
| On-prem, regulated | Self-managed or vendor Kubernetes (OpenShift, Rancher) | Control |
| Spiky event-driven functions | Serverless | Scale to zero per request |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One Laravel image, one Deployment of 3 Octane pods behind a Gateway, one migration Job per release, one scheduler pod, Horizon for queues, PostgreSQL and Redis managed outside the cluster. Kubernetes buys rolling deploys, self-healing and autoscaling; it does not change the code. The important work is making the process stateless (sessions, cache, files out of the pod) and making shutdown graceful.
Modular monolith: boundaries without the network
Still one image, but several Deployments from it: web, api, horizon-emails, horizon-reports, each with its own resources, HPA and PDB. This is "deployment-level modularity" without splitting the codebase (Modular Monolith): a heavy report queue can no longer starve web pods of CPU, and each module's workers can scale on their own queue.
Microservices: every arrow is a Service
Each service is a Deployment + Service + HPA + PDB + NetworkPolicy + ServiceAccount, released independently through GitOps. Calls go orders -> http://payments.payments.svc.cluster.local (ClusterIP, CoreDNS); discovery is solved by the platform (Service Discovery), but timeouts, retries and idempotency are not (Timeouts, Retries & Jitter). Long-lived HTTP/2/gRPC connections need L7 balancing (mesh or headless + client-side). mTLS between pods comes from a mesh or SPIFFE identities (Mutual TLS).
Distributed data: replicas, caches, regions
Stateful systems in the cluster need StatefulSets, per-zone volumes, anti-affinity across zones and an operator that understands the product's replication; a pod rescheduled to another zone cannot take its EBS volume along. Many teams keep databases managed and outside the cluster. Multi-region means multiple clusters (one per region) with global load balancing in front (IP, DNS & GeoDNS) and replication in the data tier (Replication Topologies); Kubernetes itself does not span regions well because etcd needs low latency.
Scaling path: 1x, 10x, 100x
| Load | Cluster shape | What changes |
|---|---|---|
| 1x | 3 nodes over 3 zones, 3 web pods | Probes, PDB, graceful shutdown, managed DB |
| 10x | HPA to 30 pods, KEDA for workers, Karpenter for nodes | Connection pooling, topology spread, image pull time |
| 100x | Several clusters (per region or per tier), GitOps fleet, cells | Control-plane limits (pods per node, endpoints, etcd size), cell architecture, global LB |
Lab: rollouts, QoS and shutdown budgets, with numbers
Steps 1–3 run on the host (Go only, measured). Steps 4–6 need a cluster and are expected, not run.
cd docs/snippets/system-design/containers-kubernetes/go
gofmt -l . && go vet ./... && go test ./...
# ok academy/containers-kubernetes/lifecycle
# ok academy/containers-kubernetes/probes
# ok academy/containers-kubernetes/qos
# ok academy/containers-kubernetes/reconcile
go run ./cmd/k8ssim 1) Rolling update, measured output of k8ssim
1 replicas=10 maxSurge=25% maxUnavailable=25% -> at most 13 pods, at least 8 ready
2 tick created deleted total ready new old
3 0 3 2 11 8 3 8
4 1 2 3 10 8 5 5
5 2 3 2 11 8 8 3
6 3 2 3 10 8 10 0
7 4 0 0 10 10 10 0 converged after 5 passes
2) maxSurge=1, maxUnavailable=0, 4 replicas: total alternates 5/4, ready never below 4, converged after 8 passes
3) broken image: stalls at total 13, ready 8, new 5, old 8 -> Progressing=False after progressDeadlineSeconds
4) QoS: no resources -> BestEffort; req 250m/256Mi lim 1/512Mi -> Burstable; req = lim 500m/512Mi -> Guaranteed
5) budgets (grace 30s): preStop 5 + shutdown 20 -> fits; drain 5 + shutdown 20 -> fits;
preStop 10 + drain 5 + shutdown 20 -> SIGKILL risk (need 37s, have 30s)# 4) Watch a real rollout (expected, not run)
kubectl -n shop set image deploy/orders orders=registry.example.com/orders:1.9.0
kubectl -n shop rollout status deploy/orders --timeout=10m
# Waiting for deployment "orders" rollout to finish: 1 out of 3 new replicas have been updated...
# deployment "orders" successfully rolled out
# 5) Prove zero 502s during the rollout (expected, not run)
echo "GET https://shop.example.com/orders" | vegeta attack -rate=200 -duration=120s | vegeta report
# Status Codes [code:count] 200:24000 <- with probes + drain; without them expect some 502/503
# 6) Drain a node with a PDB in place (expected, not run)
kubectl drain node-a --ignore-daemonsets --delete-emptydir-data
# evicting pod shop/orders-7d9-abc
# error when evicting pods/"orders-7d9-def" -n "shop" (will retry after 5s): Cannot evict pod as it would violate the pod's disruption budget.
# node/node-a drainedCommon misconceptions
| Belief | Reality |
|---|---|
| A container is a small VM | A process on the shared host kernel, isolated by namespaces and limited by cgroups |
| Deleting a file in a later layer shrinks the image | Layers are additive; the file stays in the earlier layer |
latest is fine if you redeploy | Tags move; deploy immutable tags or digests |
kubectl apply means deployed | It stores desired state; controllers converge later; check rollout status |
| Running = serving | Traffic follows the Ready condition |
| Liveness should check the database | Liveness restarts; dependency failures belong to readiness |
| Kubernetes removes the pod from the Service before SIGTERM | Both start together; drain for a few seconds |
| Secrets are encrypted | base64 in etcd unless encryption at rest is configured |
| CPU limits make things safer | They cause throttling; memory limits are the important ceiling |
| A PDB protects against node failures | Only voluntary evictions through the Eviction API |
| A Service balances every request | ClusterIP balances connections; long-lived connections stick |
| An Ingress object is enough | You need a controller; Ingress is frozen and Ingress NGINX is retired |
| StatefulSet = HA database | It gives identity and disks; replication and failover come from the database or operator |
| Everyone should run Kubernetes | Managed container platforms are cheaper for small fleets |
Cheat sheet
| Topic | Remember |
|---|---|
| Container | Namespaces (view) + cgroups (limits) + image layers; shares the kernel |
| Image | OCI manifest + config + layers; pin by digest; multi-arch index |
| Dockerfile | Multi-stage, non-root, distroless/slim, exec form, .dockerignore, no secrets |
| Control plane | apiserver (only one talking to etcd), scheduler, controller manager; pods survive its outage |
| Model | Declarative spec, observed status, level-triggered reconcile loops |
| Deployment | 25%/25% default; maxUnavailable: 0 for zero-downtime; alert on ProgressDeadlineExceeded |
| StatefulSet | Ordinals, headless Service, volumeClaimTemplates, partition |
| Job/CronJob | backoffLimit 6, backoff capped at ten minutes, ttlSecondsAfterFinished, concurrencyPolicy: Forbid |
| Config | ConfigMap/Secret ≤ 1 MiB; env needs restart; Downward API for pod facts |
| Resources | Request = scheduling, limit = ceiling; QoS Guaranteed/Burstable/BestEffort |
| Probes | Startup gates; liveness local only; readiness for traffic; defaults 10 s / 1 s / 3 |
| Restarts | 10 s doubling to 300 s, reset after 10 min |
| Shutdown | preStop + drain + shutdown + margin ≤ grace (30 s default); SIGKILL = 137 |
| Autoscaling | HPA every 15 s, 0.1 tolerance, 300 s scale-down window; KEDA for queues; Karpenter for nodes |
| Traffic | ClusterIP / NodePort / LoadBalancer / ExternalName / headless; Gateway API over Ingress |
| Security | Least-privilege RBAC, one ServiceAccount per app, IRSA/Workload Identity, PSS restricted, seccomp, KMS encryption |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What exactly isolates a container from its neighbours, and what does it still share? Must-know
Answer
Answer: Linux namespaces isolate its view (PID, mount, network, UTS, IPC, user, cgroup, time) and cgroups limit its resources; it still shares the host kernel, so kernel bugs and privileged settings can break out.
2 — Why does deleting a secret file in a later Dockerfile step not protect it? Must-know
Answer
Answer: Layers are additive tar changesets; the later layer only adds a whiteout entry, and the earlier layer with the file is still in the image and can be extracted.
3 — The control plane is down for ten minutes. What keeps working and what does not? Important
Answer
Answer: Running pods keep serving and kube-proxy rules stay in place. Nothing changes: no scheduling, no replacement of failed pods on other nodes, no scaling, no rollouts, no endpoint updates.
4 — A Deployment has 10 replicas and default strategy. What are the most pods and the fewest ready pods during a rollout? Important
Answer
Answer: maxSurge 25% rounds up to 3, maxUnavailable 25% rounds down to 2: at most 13 pods, at least 8 available.
5 — Why is checking PostgreSQL in a liveness probe harmful? Must-know
Answer
Answer: A database outage makes every pod fail liveness at the same time, so all are restarted, pay a cold start and may still be starting when the database returns; restarting cannot fix the database. Put the check in readiness if anywhere.
6 — What must hold for a pod to be Guaranteed, and why does it matter? Important
Answer
Answer: Every container must have CPU and memory limits with requests equal to them. Guaranteed pods within their requests are the last evicted under node pressure.
7 — Your pods get 502s for a few seconds on every deploy. What is happening and what is the fix? Must-know
Answer
Answer: Endpoint removal and SIGTERM start at the same time, and kube-proxy, the ingress and cloud LBs update later; the app exits while traffic still arrives. Fail readiness, keep serving for a drain delay (or preStop sleep), then shut down gracefully within the grace period.
8 — A pod shows CrashLoopBackOff with 7 restarts. Where do you look and how long until the next attempt? Must-know
Answer
Answer: kubectl logs --previous and the last terminated state (exit code, reason); restart delays double from 10 s up to a 300 s cap, so the next try is up to 5 minutes away.
9 — Why does a kubectl drain hang on a single-replica Deployment with minAvailable: 1? Important
Answer
Answer: The Eviction API refuses (429) any eviction that would drop below the budget, and with one replica every eviction does; run two replicas or relax the PDB.
10 — When does KEDA beat a CPU-based HPA for Laravel queue workers? Important
Answer
Answer: When backlog, not CPU, is the signal: workers waiting on I/O show low CPU while the queue grows. KEDA scales on queue length (down to zero) by feeding external metrics to the HPA.
11 — Why prefer Gateway API over Ingress for a new cluster? Good to know
Answer
Answer: Ingress is frozen and controller features live in non-portable annotations; Gateway API is the recommended, role-oriented API with weights, header matching and cross-namespace routes, and Ingress NGINX is retired.
12 — When should you not use Kubernetes? Must-know
Answer
Answer: For a few services without a team to run the platform: ECS, Cloud Run, Azure Container Apps or Fly.io run the same images without the control plane, add-ons and upgrade cycle.
Glossary
| Term | Meaning |
|---|---|
| Container | A process isolated by namespaces and limited by cgroups, started from an image |
| Namespace (Linux) | Kernel feature giving a process its own view of PIDs, mounts, network, users, hostname, IPC, cgroups, time |
| Namespace (Kubernetes) | A scope for object names, RBAC and quotas inside a cluster |
| cgroup | Kernel control group limiting and accounting CPU, memory, PIDs, I/O |
| Image | OCI manifest + configuration + filesystem layers, addressed by digest |
| Layer | A tar changeset; removals are whiteout files |
| OCI | Open Container Initiative: image, runtime and distribution specs |
| Dockerfile | Build recipe for an image |
| Multi-stage build | Several FROM stages; copy only artefacts to the final one |
| Non-root | Running the container process with a non-zero UID |
| Distroless | Base images with only the app's runtime dependencies, no shell or package manager |
.dockerignore | Exclusion list for the build context |
| Image scanning | Matching an image's packages against vulnerability databases (Trivy, Grype) |
| Registry | Server storing and distributing images (ECR, Artifact Registry, Harbor) |
| Rootless | Container engine and containers running without root privileges |
| Kubernetes | Container orchestrator built on a declarative API and controllers |
| Control plane | API server, etcd, scheduler, controller manager (and cloud controller manager) |
| API server | kube-apiserver: authn, authz, admission, validation; the only etcd client |
| etcd | Raft-based key-value store holding all cluster state |
| Scheduler | kube-scheduler: binds unscheduled pods to nodes by filtering and scoring |
| Controller manager | kube-controller-manager: runs the built-in reconciliation loops |
| kubelet | Node agent that runs pods, probes and reports status |
| kube-proxy | Node agent that programs Service rules (iptables, nftables, ipvs) |
| containerd | CNCF container runtime used by most Kubernetes nodes |
| CRI | Container Runtime Interface: gRPC API between kubelet and runtime |
| Reconciliation loop | Observe, compare with desired state, act; level-triggered |
| Declarative | Describe the desired end state, not the steps |
| Operator / CRD | Custom controller for your own resource types |
| Pod | Smallest schedulable unit: containers sharing network and volumes |
| Init / sidecar container | Runs before the app / runs alongside it (restartPolicy: Always) |
| Deployment | Manages ReplicaSets and rolling updates for stateless pods |
| ReplicaSet | Keeps N pods of one template |
| Rolling update | Replace pods gradually within surge/unavailable bounds |
| maxSurge | Extra pods allowed above replicas during rollout (rounds up) |
| maxUnavailable | Pods allowed below replicas during rollout (rounds down) |
progressDeadlineSeconds | Time before a rollout is marked ProgressDeadlineExceeded |
| StatefulSet | Pods with stable ordinals, DNS and per-pod PVCs |
| Headless Service | clusterIP: None; DNS returns pod IPs |
| DaemonSet | One pod per matching node |
| Job | Run pods to completion with retries |
| CronJob | Create Jobs on a cron schedule |
backoffLimit | Retries before a Job fails (default 6) |
parallelism | Pods of a Job running at once |
ttlSecondsAfterFinished | Auto-delete a finished Job after N seconds |
| ConfigMap | Non-secret configuration object (≤ 1 MiB) |
| Secret | Configuration object for sensitive data; base64, not encrypted by default |
| Downward API | Exposes pod metadata and resources to containers |
| Requests | Resources reserved for scheduling |
| Limits | cgroup ceilings: CPU throttled, memory OOM-killed |
| QoS class | Guaranteed, Burstable or BestEffort, derived from requests/limits |
| Guaranteed | Requests equal limits for CPU and memory in every container |
| Burstable | Some requests or limits, not Guaranteed |
| BestEffort | No requests or limits at all; evicted first |
| Node affinity | Rules matching node labels |
| Pod anti-affinity | Rules keeping pods apart by topology |
| Taint / toleration | Node repels pods unless they tolerate the taint |
| Topology spread constraint | Even distribution across zones/nodes with maxSkew |
| PodDisruptionBudget | Floor on available pods during voluntary evictions |
| Priority class / preemption | Pod priority; higher-priority pending pods can evict lower ones |
| Liveness probe | Failure restarts the container |
| Readiness probe | Failure removes the pod from Service endpoints |
| Startup probe | Gates the other probes until the app has started |
restartPolicy | Always, OnFailure or Never |
| CrashLoopBackOff | Waiting state between restarts of a crashing container |
| Eviction | Removing a pod for node pressure or through the Eviction API |
| Node pressure | MemoryPressure, DiskPressure, PIDPressure conditions |
| SIGTERM | Polite stop signal sent at pod termination |
terminationGracePeriodSeconds | Time between the start of termination and SIGKILL (default 30) |
| preStop | Lifecycle hook run before SIGTERM, inside the grace period |
| HPA | HorizontalPodAutoscaler: replica count from metrics |
| VPA | VerticalPodAutoscaler: requests from observed usage |
| KEDA | Event-driven autoscaler feeding external metrics to the HPA, scale to zero |
| Cluster Autoscaler | Resizes node groups for pending pods and idle nodes |
| Karpenter | Provisions right-sized nodes from pending pods; consolidates |
| Service | Stable name and virtual IP for a set of pods |
| ClusterIP / NodePort / LoadBalancer / ExternalName | Service types: internal VIP / node port / cloud LB / DNS alias |
| EndpointSlice | List of pod addresses and conditions behind a Service |
| Ingress / Ingress controller | Frozen HTTP routing API / the proxy implementing it |
| Gateway API | GatewayClass, Gateway, HTTPRoute, GRPCRoute: the successor to Ingress |
| NetworkPolicy | Label-based allow rules enforced by the CNI |
| PersistentVolume / PersistentVolumeClaim | A disk / a pod's request for one |
| StorageClass | How to provision volumes dynamically |
| CSI | Container Storage Interface for storage drivers |
| Access mode | RWO, ROX, RWX, RWOP |
| Blue/green / canary | Switch all at once / shift traffic gradually with analysis |
| Argo Rollouts / Flagger | Progressive delivery controllers |
| GitOps / Argo CD / Flux | Cluster state reconciled from Git / two GitOps controllers |
| Helm / Kustomize | Chart templating and release tool / template-free overlays |
| metrics-server / kube-state-metrics | Live resource metrics for autoscaling / object state as metrics |
| RBAC | Role-based access control for the Kubernetes API |
| ServiceAccount | Identity of a workload |
| IRSA / Workload Identity | EKS / GKE mapping of ServiceAccounts to cloud IAM |
| Pod Security Standards | privileged, baseline, restricted profiles enforced by namespace labels |
| seccomp | Kernel syscall filter; RuntimeDefault profile |
| Octane / FrankenPHP / php-fpm | Laravel app server / Caddy-based PHP server / classic FastCGI process manager |
schedule:work | Laravel command that runs the scheduler every minute in the foreground |
| ECS / Cloud Run | AWS and Google managed container platforms |
References
- Burns, Grant, Oppenheimer, Brewer, Wilkes. Borg, Omega, and Kubernetes. ACM Queue 14(1), 2016. research.google, PDF
- Linux man pages: namespaces(7), cgroups(7)
- OCI: Image Format Specification, Filesystem Layers
- Docker: Building best practices, Multi-stage builds, Build context and .dockerignore, Rootless mode
- GoogleContainerTools/distroless, Trivy, containerd
- Kubernetes architecture: Components, Cluster Architecture, Controllers, CRI, Objects, Object management, Releases
- Workloads: Pod Lifecycle, Termination of Pods, Container Lifecycle Hooks, Deployments, ReplicaSet, StatefulSets, DaemonSet, Jobs, CronJob, TTL after finished, Images
- Configuration: ConfigMaps, Secrets, Downward API, Resource Management, Pod QoS
- Scheduling and disruption: Assigning Pods to Nodes, Taints and Tolerations, Topology Spread, Disruptions, Configure a PDB, API-initiated Eviction, Priority and Preemption, Node-pressure Eviction
- Probes: Probes concept, Configure probes
- Autoscaling: Autoscaling Workloads, HPA, HPA walkthrough, VPA, KEDA concepts, KEDA Redis Lists scaler, Cluster Autoscaler FAQ, Karpenter docs, Karpenter concepts, metrics-server, kube-state-metrics, Resource metrics pipeline
- Networking: Service, EndpointSlices, Virtual IPs and proxy modes, Ingress, Ingress Controllers, Gateway API (concept), Gateway API project, Network Policies, Ingress NGINX retirement, Ingress NGINX docs, Traefik Kubernetes Ingress, HAProxy Kubernetes Ingress Controller
- Storage: Persistent Volumes, Storage Classes
- Security: Pod Security Standards, RBAC, Service Accounts, Encrypting data at rest, seccomp tutorial, IRSA (Amazon EKS), Workload Identity Federation for GKE
- Delivery: Argo Rollouts, Argo Rollouts canary, Argo CD, Flux, Flagger, Helm: Using Helm, Helm: Charts, Kustomize reference, Kustomize introduction, Kustomize in kubectl
- Alternatives: Amazon ECS, Cloud Run, Fly.io docs
- Laravel 13: Deployment, Octane, Horizon, Task Scheduling, Configuration, Migrations, Artisan, Requests (trusted proxies), Filesystem, Session, Queues; FrankenPHP Docker images
- Go: os/signal, net/http