Summary#
A container packages an application with its dependencies, such as libraries, runtime and configuration defaults, into an image. It runs as an isolated process that shares the host's operating-system kernel. Containers start in milliseconds to seconds, are small (megabytes, not gigabytes), and behave the same on a laptop, in CI and in production. That's the "works on my machine" fix. Docker popularised them. Images are built from stacked, cached, content-addressed layers, and stored in registries.
Kubernetes (K8s) is a container orchestrator. You declare the desired state ("run 6 replicas of checkout:v42, each with 500m CPU and 512 MiB, reachable at checkout:80"), and Kubernetes keeps reality matching it. It schedules containers onto machines, restarts them when they crash, replaces failed nodes, rolls out new versions, load-balances traffic, scales on demand, and injects configuration and secrets. Its parts:
- a control plane: the API server, etcd, the scheduler and controllers;
- worker nodes, running the kubelet and a container runtime;
- pods, its smallest unit: one or more tightly coupled containers.
Deployments manage stateless pods. Services (ClusterIP, NodePort, LoadBalancer) and Ingress route traffic. The HPA and cluster autoscaler scale pods and nodes. ConfigMaps and Secrets hold configuration. Patterns such as sidecar, init and ambassador containers compose pods.
Kubernetes is powerful, but it's operationally heavy. For small systems, serverless platforms or managed container services are often the better choice.
Why It Exists#
Before containers, deploying meant configuring servers: install the right Python or Java version, the system libraries, the configuration files, and then copy the code. Servers drifted apart ("snowflakes"), deploys broke because staging had a different OpenSSL version, and running two apps with conflicting dependencies on one machine was painful. Virtual machines fixed isolation, but each carries a full operating system. They take minutes to boot, gigabytes of disk, and hundreds of MB of RAM of overhead, so packing many small services onto hardware was wasteful.
Containers gave a standard, immutable unit of deployment. You build once, and run the identical artefact everywhere. Dependencies travel with the app. Many containers share one kernel efficiently, and starting a new copy takes seconds, which makes autoscaling and fast rollbacks practical.
Running thousands of containers across hundreds of machines raises new problems, though:
- Which machine has room for this one?
- What happens when a machine dies at 3 a.m.?
- How do services find each other when IPs change on every restart?
- How do you roll out v43 without downtime, and roll back if it's bad?
- How do you scale for the evening peak?
Doing that by hand, or with scripts, doesn't scale. Kubernetes answers all of these with one declarative API and a set of control loops. It grew out of Google's experience running containers at enormous scale on its internal Borg system (Verma et al., "Large-scale cluster management at Google with Borg", EuroSys 2015). Google open-sourced it in 2014, and donated it to the then-new Cloud Native Computing Foundation (CNCF) in 2015.
How It Works#
Containers vs VMs#
A virtual machine emulates a whole computer. A hypervisor (VMware ESXi, KVM, Xen, Hyper-V, or AWS Nitro) runs several guest operating systems, each with its own kernel, on one physical host. A container is just a normal Linux process (or group of processes), which the kernel isolates so it thinks it has its own machine. There's no guest kernel. All containers on a host share the host kernel.
| Aspect | Virtual machine | Container |
|---|---|---|
| Isolation boundary | Hardware virtualisation; separate kernel per VM | Kernel namespaces and cgroups; shared host kernel |
| Startup time | Tens of seconds to minutes (boot an OS) | Milliseconds to a few seconds (start a process) |
| Size | GBs (full OS image) | MBs to hundreds of MBs (app plus userland libraries) |
| Density | Tens of VMs per host | Hundreds of containers per host |
| Overhead | Guest OS memory and CPU per VM | Near-native; only the app's own usage |
| Security isolation | Strong: a kernel exploit in a guest doesn't reach the host easily | Weaker: a kernel exploit can escape to the host; needs hardening |
| OS flexibility | Any OS per VM (Windows next to Linux) | Same kernel family as the host (Linux containers on Linux) |
| Typical use | Multi-tenant clouds, legacy apps, strong isolation | Microservices, CI jobs, dense packing, fast scaling |
They are complementary, not rivals. In the cloud, your containers usually run inside VMs. EKS, GKE and AKS worker nodes are VMs. The VM gives strong tenant isolation from other cloud customers, and containers give efficient packing within your VM.
Containers vs VMs, in depth: namespaces, cgroups, runtimes and sandboxed containers#
The kernel features behind containers.
- Namespaces give a process its own view of a system resource:
- PID, so the container sees its main process as PID 1;
- mount, its own filesystem tree;
- network, its own interfaces, IPs, routing tables and ports;
- UTS, its own hostname;
- IPC;
- user, which maps container root to an unprivileged host user;
- cgroup.
- Control groups (cgroups) limit and account resources: CPU shares and quotas, memory limits (exceeding one triggers the out-of-memory killer, so a pod shows
OOMKilled), I/O bandwidth, and PIDs. cgroup v2 is now the default in modern distributions. - Union, or overlay, filesystems (OverlayFS) stack read-only image layers with a thin writable layer on top. Many containers from the same image share the read-only layers on disk and in the page cache.
- Security features: seccomp filters system calls, capabilities split root's powers (drop
NET_RAW,SYS_ADMIN, and so on), and AppArmor/SELinux profiles confine file and network access.
The runtime stack.
- The OCI (Open Container Initiative, founded 2015) standardises the image format and runtime specification, so images built by Docker run under any compliant runtime.
- runc is the low-level runtime. It sets up namespaces and cgroups, and executes the process.
- containerd and CRI-O are the high-level runtimes. They pull images, manage snapshots, and supervise containers.
- Kubernetes talks to them through the CRI (Container Runtime Interface).
Kubernetes removed its built-in Docker Engine shim ("dockershim") in version 1.24 (2022). Clusters run containerd or CRI-O directly, and Docker-built images still work, because they're OCI images.
Docker's architecture. The docker CLI talks to the Docker daemon (dockerd) over a REST API. The daemon builds images, manages networks and volumes, and delegates running containers to containerd and runc. Registries (Docker Hub, GitHub Container Registry, Amazon ECR, Google Artifact Registry, Harbor) store images. docker run nginx resolves the tag, pulls any missing layers, creates a container from the image plus a writable layer, sets up networking (a bridge network with NAT by default), and starts the entrypoint. Docker Compose describes multi-container apps in YAML for local development.
Sandboxed containers. Shared-kernel isolation isn't enough when running untrusted code: multi-tenant platforms, CI runners for public repositories, code-execution services. Options include:
- gVisor (Google), a user-space kernel that intercepts system calls;
- Kata Containers, lightweight VMs per pod;
- Firecracker (AWS), a microVM monitor that boots in about 125 ms, behind AWS Lambda and Fargate (Agache et al., "Firecracker: Lightweight Virtualization for Serverless Applications", NSDI 2020).
They give VM-grade isolation with near-container speed, at some cost in performance and compatibility. Kubernetes selects them per pod with a RuntimeClass.
Containers are not a security boundary by default. Running as root, with privileged mode, host mounts (especially /var/run/docker.sock) or host networking, makes escape easy. Harden with a non-root user, a read-only root filesystem, dropped capabilities, the default seccomp profile, no privilege escalation, and user namespaces where supported.
Docker images and layers#
An image is a read-only template: a stack of filesystem layers, plus metadata (entrypoint, environment, exposed ports, user). It is built from a Dockerfile. Each instruction that changes the filesystem (RUN, COPY, ADD) creates a new layer, holding just the files that instruction added, changed or deleted. Layers are content-addressed, identified by the SHA-256 digest of their contents. So:
- Layers are shared. Twenty images built on the same
node:22-slimbase store and pull its layers once. - Builds are cached. If an instruction and its inputs are unchanged, the builder reuses the cached layer. Once one layer changes, every layer after it is rebuilt. Order instructions from least to most frequently changing.
- Images are immutable, and can be referenced by digest (
checkout@sha256:9f2c…), which always means exactly the same bytes. Tags such as:latestor:v42are mutable pointers. Deploy by digest, or by unique immutable tags.
A good multi-stage Dockerfile for a Node.js service:
# ---- build stage: has compilers and dev deps, discarded afterwards ----
FROM node:22-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./ # changes rarely -> cached layer
RUN npm ci # deps layer reused until lockfile changes
COPY . . # source changes often -> later layer
RUN npm run build && npm prune --omit=dev
# ---- runtime stage: minimal, non-root, no shell or package manager ----
FROM gcr.io/distroless/nodejs22-debian12
WORKDIR /app
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
USER nonroot
EXPOSE 8080
CMD ["dist/server.js"]The build stage holds compilers and dev dependencies, and is discarded. The final image contains only the runtime, the production dependencies and the compiled code. That often shrinks an image from about 1 GB to about 100–150 MB, which cuts pull time, cold starts and vulnerability surface.
Docker images, in depth: build caching, best practices and supply-chain safety#
Docker best practices, each with its reason:
- Use small, trusted base images:
-slim, Alpine (but watch musl libc compatibility), distroless, or Chainguard/Wolfi images. Fewer packages means fewer CVEs and faster pulls. - Use multi-stage builds to keep build tools out of runtime images.
- Order layers for caching: dependency manifests first, then install, then source. Combine related
RUNsteps, and clean package caches in the same layer (apt-get install … && rm -rf /var/lib/apt/lists/*). A file deleted in a later layer still exists in the earlier one. - Use a
.dockerignoreto keep.git,node_modules, secrets and local files out of the build context. - Never bake secrets into images. Layers are forever, and anyone who can pull the image can read every layer. Use BuildKit secret mounts (
RUN --mount=type=secret,...) for build-time credentials, and runtime injection for app secrets. - Run as non-root, with a
USERinstruction. - Have one process per container, logging to stdout and stderr. Handle
SIGTERMfor graceful shutdown. Use a small init, such astini, if the app spawns children, because PID 1 doesn't get default signal handling. - Pin versions: base image digests and package versions, for reproducible builds. Use Dependabot or Renovate to update them deliberately.
- Scan and sign: run Trivy, Grype or registry scanning in CI, generate an SBOM, and sign images with cosign, so clusters can verify provenance.
BuildKit is the modern builder. It runs independent stages in parallel, has cache mounts (RUN --mount=type=cache,target=/root/.npm) that persist package caches between builds without putting them in layers, exports remote caches (to a registry) for CI, and builds multi-platform images (linux/amd64 and linux/arm64) with docker buildx. That matters, because ARM instances such as AWS Graviton are often cheaper per unit of work.
Image size and startup. A node pulling a 1.2 GB image over a 1 Gbit/s link spends about 10 seconds or more just downloading it, and that's per node, during scale-out. Mitigations:
- smaller images;
- shared base layers already cached on nodes;
- image pre-pulling on node startup (DaemonSets or node images with the common bases);
- lazy-loading snapshotters such as stargz/SOCI, which start containers before the whole image arrives;
- regional registries or pull-through caches, so nodes don't pull across regions or from Docker Hub (which rate-limits anonymous pulls).
Reproducibility and provenance. Two builds from the same source should produce the same image digest. That needs pinned inputs, and normalised timestamps (SOURCE_DATE_EPOCH). With SLSA provenance attestations and signatures, an admission controller can enforce "only images built by our CI, from our repository, signed, and with no critical CVEs may run in prod".
Kubernetes architecture: control plane, nodes and pods#
A Kubernetes cluster is a set of machines split into two roles.
The control plane (the "brain") stores desired state and drives the cluster towards it.
- kube-apiserver is the front door. Every component, and every
kubectlcommand, reads and writes cluster state through its REST API. It authenticates and authorises requests (RBAC), runs admission controllers that validate or mutate objects (inject sidecars, enforce policies), and persists objects to etcd. It is stateless, and scales horizontally behind a load balancer. - etcd is a strongly consistent, distributed key-value store, using the Raft consensus algorithm. It is the cluster's single source of truth: every Deployment, Pod, Service, ConfigMap and Secret is stored there. It usually runs as 3 or 5 members, to tolerate 1 or 2 failures (ZooKeeper and etcd).
- kube-scheduler watches for pods with no node assigned, and picks a node for each. It filters out nodes that can't fit the pod (insufficient CPU or memory, taints, affinity rules, volume zones), then scores the rest (spreading, resource balance, image locality), and binds the pod to the best one.
- kube-controller-manager runs the built-in controllers. Each is a control loop for one resource type: the ReplicaSet controller keeps N pods, the Deployment controller manages rollouts, and there are Node, Job, EndpointSlice, ServiceAccount and other controllers.
- cloud-controller-manager integrates with the cloud provider. It creates cloud load balancers for
LoadBalancerServices, attaches node metadata, and sets up routes.
Worker nodes (the "muscle") run the workloads.
- kubelet is the node agent. It watches the API for pods assigned to its node, tells the container runtime to start them, mounts volumes, runs health probes, and reports pod and node status back.
- The container runtime, containerd or CRI-O, pulls images and runs containers.
- kube-proxy (or an eBPF replacement such as Cilium) programs the node's networking, so Service virtual IPs reach the right pods.
- A CNI plugin (Calico, Cilium, AWS VPC CNI, Flannel) gives every pod its own IP address, and enforces NetworkPolicies.
Pods are the smallest deployable unit. A pod is one or more containers that are always scheduled together on the same node. They share a network namespace (one IP address, and they reach each other over localhost) and can share volumes. Most pods hold one application container, plus perhaps a helper (see the patterns below). Pods are ephemeral and disposable. They get new IPs when recreated, and you almost never create them directly. Higher-level controllers (Deployments, StatefulSets, Jobs) create and replace them.
The core idea is reconciliation. You don't tell Kubernetes what to do. You tell it what you want, by writing an object's spec. Controllers continuously compare the spec with the observed status, and act to close the gap. If a node dies, its pods disappear from the status, and the ReplicaSet controller sees 4 running pods out of the 6 desired, so it creates 2 more. The scheduler places them, and kubelets start them. Nobody wrote a "handle node failure" script. This level-triggered design (react to the current state, not to individual events) makes the system self-healing, and robust to missed events and restarts.
Kubernetes architecture, in depth: what happens on kubectl apply, watches and control-plane scaling#
The journey of a Deployment.
Every component works by watching the API server. Watches are long-lived streams of changes, keyed by etcd's resourceVersion. Components keep local caches (informers) and work queues, so they don't poll. Controllers are idempotent: they compute "desired minus actual", and act. That's also why you can extend Kubernetes. A CustomResourceDefinition (CRD) adds a new object type (say, PostgresCluster), and an operator is a custom controller that reconciles it: creating StatefulSets, configuring replication, running backups, handling failover. Operators encode operational knowledge as code. Examples are CloudNativePG, Strimzi for Kafka, ECK for Elasticsearch, and the Flink Kubernetes Operator.
Running clustered systems on Kubernetes. Stateful distributed systems keep their own internal architecture inside pods.
- An Elasticsearch cluster has master-eligible nodes (which elect one active master that manages cluster state, index creation and shard allocation), data nodes (which hold shards and replicas, and can be tiered hot, warm and cold), and coordinating and ingest nodes. On Kubernetes, each role becomes its own StatefulSet. Data nodes get fast persistent volumes, and are pinned to node pools with the right disks and memory. Masters get small, stable pods.
- Flink has a JobManager (coordination, checkpoint triggering, scheduling) and TaskManagers, whose task slots run the parallel operator instances. On Kubernetes, TaskManagers are pods sized to their slots. The operator handles savepoints and upgrades.
In both cases, Kubernetes provides placement, restarts and storage attachment. The application's own leader election, sharding and replication still provide correctness. The two layers must agree. A PodDisruptionBudget must stop Kubernetes draining two of three Elasticsearch masters at once.
Control-plane limits and failure modes.
- Kubernetes officially supports clusters of up to about 5,000 nodes and 150,000 pods (the published scalability thresholds). Large companies run many clusters rather than one giant one, for blast radius and upgrade safety.
- etcd is the usual bottleneck. It should run on low-latency SSDs, its database has a default size quota of 2 GB (configurable up to about 8 GB), and huge objects or very high churn (thousands of pod creations per second) stress it. Use dedicated etcd nodes for big clusters, compact and defragment it regularly, and back it up. Losing etcd without a backup means losing the cluster's state.
- The API server can be overwhelmed by poorly written controllers that list everything repeatedly. API Priority and Fairness queues requests per client, so one misbehaving client can't starve the kubelets.
- If the control plane goes down, existing pods keep running. Kubelets and kube-proxy keep working from their last known state. But nothing gets rescheduled, scaled or updated until it's back. That's why managed control planes (EKS, GKE, AKS) run multi-AZ, with an SLA.
Deployments#
A Deployment manages a set of identical, stateless pods. It owns a ReplicaSet (which keeps exactly N pod replicas from a template), and manages changes to it. When you update the pod template, for example with a new image, the Deployment creates a new ReplicaSet and gradually shifts replicas from the old to the new: a rolling update. Two settings control the pace:
maxSurge: how many extra pods may exist above the desired count during the rollout, for example 25%;maxUnavailable: how many may be missing, for example 0, for no capacity loss.
Kubernetes only removes old pods as new ones become Ready, so the readiness probe gates the rollout. If new pods never become ready, the rollout stalls, rather than taking the service down. kubectl rollout undo switches back to the previous ReplicaSet, which is kept for that purpose (revisionHistoryLimit).
apiVersion: apps/v1
kind: Deployment
metadata: { name: checkout, labels: { app: checkout } }
spec:
replicas: 6
strategy: { type: RollingUpdate, rollingUpdate: { maxSurge: 25%, maxUnavailable: 0 } }
selector: { matchLabels: { app: checkout } }
template:
metadata: { labels: { app: checkout } }
spec:
topologySpreadConstraints: # spread replicas across zones
- { maxSkew: 1, topologyKey: topology.kubernetes.io/zone,
whenUnsatisfiable: DoNotSchedule, labelSelector: { matchLabels: { app: checkout } } }
containers:
- name: app
image: registry.example.com/checkout@sha256:9f2c0d # immutable digest
ports: [{ containerPort: 8080 }]
resources:
requests: { cpu: 500m, memory: 512Mi } # scheduler reserves this
limits: { memory: 512Mi } # OOM-kill above this
readinessProbe: { httpGet: { path: /ready, port: 8080 }, periodSeconds: 5 }
livenessProbe: { httpGet: { path: /live, port: 8080 }, initialDelaySeconds: 20 }
lifecycle: { preStop: { sleep: { seconds: 10 } } } # drain before SIGTERM
terminationGracePeriodSeconds: 40Key ideas in this manifest:
-
Requests and limits. Requests are what the scheduler reserves, and they decide placement. Limits cap usage: exceeding a memory limit gets the container killed (
OOMKilled), and CPU above its limit is throttled. Requests equal to limits gives the "Guaranteed" QoS class, the last to be evicted under node pressure. Many teams set memory limits equal to requests, and no CPU limit, to avoid needless throttling while requests still guarantee a fair share. -
Probes.
- Readiness: "send me traffic?" Failing removes the pod from Service endpoints, without restarting it.
- Liveness: "am I stuck?" Failing restarts the container.
- Startup: this protects slow starters from liveness kills until they've started.
Never make liveness depend on downstream services. A database blip would then restart every pod at once, turning a dependency outage into a total one.
-
Graceful shutdown. On termination, Kubernetes removes the pod from endpoints, and, at the same time, sends
SIGTERM. Endpoint removal takes a moment to propagate to every node and load balancer, so apreStopsleep of 5–15 seconds avoids dropped requests. The app should then stop accepting new connections, finish in-flight work, and exit beforeterminationGracePeriodSeconds. -
Spreading. Topology spread constraints, or anti-affinity, put replicas in different zones and nodes, so one failure doesn't take out every replica (High Availability Design).
Other workload controllers:
| Controller | For | Key behaviour |
|---|---|---|
| Deployment | Stateless services (APIs, web, workers) | Interchangeable pods, rolling updates, easy scaling |
| StatefulSet | Databases, brokers, clustered stores | Stable names (kafka-0, kafka-1), stable per-pod persistent volumes, ordered start and update |
| DaemonSet | One pod per node: log agents, node exporters, CNI, storage drivers | Runs on every node (or a labelled subset) automatically |
| Job | Run-to-completion batch work | Retries failures, parallelism, completions |
| CronJob | Scheduled jobs | Creates Jobs on a cron schedule; concurrency policy |
Deployments, in depth: strategies, disruption budgets and safe rollouts#
Deployment strategies on Kubernetes:
- Recreate: kill all old pods, then start new ones. There is downtime. Use it only when two versions can't run together, for example during an exclusive schema migration.
- Rolling update (the default): a gradual swap, with no downtime if probes and shutdown are right. Both versions serve traffic for a while, so they must be compatible: an API that is backward compatible, and database migrations in expand-then-contract steps.
- Blue-green: run the full new version ("green") beside the old ("blue"), then switch the Service selector, or the Ingress or load-balancer target, at once. Rollback is instant. The cost is double capacity during the switch.
- Canary: send a small share of traffic (1%, then 5%, 25%, 100%) to the new version, and watch error and latency metrics. Plain Kubernetes can only approximate this through replica ratios. Precise percentages need an ingress controller, a service mesh or Gateway API weights. Tools such as Argo Rollouts and Flagger automate the steps, with metric analysis and automatic rollback.
- Shadow (mirroring): copy live traffic to the new version, and discard its responses. This tests real load with no user impact, for side-effect-free reads.
- A/B testing: route by user attribute (header, cookie, region) to compare versions on business metrics.
These are covered more broadly in CI/CD and Deployment.
PodDisruptionBudgets (PDBs). Voluntary disruptions (node drains for upgrades, cluster-autoscaler scale-down, spot reclamation handling) respect PDBs, for example minAvailable: 80%, or maxUnavailable: 1 for a 3-node quorum system. Without PDBs, an upgrade of the node pool can drain every replica of a service at once. With an overly strict PDB (maxUnavailable: 0), drains hang forever, and upgrades stall. Set PDBs per workload, consistent with its quorum or capacity needs.
Rollout safety checklist:
- an immutable image reference;
- readiness probes that reflect real readiness (warm caches, connection pools open);
maxUnavailable: 0for critical services;minReadySeconds, so a pod must stay ready for a while before counting;progressDeadlineSeconds, so stuck rollouts are reported;- automated canary analysis on SLIs;
- a fast, practised rollback path.
Most production incidents follow a change, so make changes small, gradual and reversible.
Service types (ClusterIP, NodePort, LoadBalancer) and Ingress#
Pods come and go, and their IPs change. A Service gives a set of pods, selected by labels such as app: checkout, a stable virtual IP and DNS name, and load-balances connections across the pods that are currently ready. Kubernetes keeps an EndpointSlice list of ready pod IPs for each Service. kube-proxy, or eBPF, programs every node, so traffic to the Service IP is forwarded to one of those pods. Cluster DNS (CoreDNS) resolves checkout.payments.svc.cluster.local, or just checkout within the same namespace.
| Type | Reachable from | How | Use for |
|---|---|---|---|
| ClusterIP (default) | Inside the cluster only | Virtual IP; kube-proxy forwards to ready pods | Service-to-service calls |
| NodePort | Outside, via <any-node-IP>:<port> (30000–32767) | Opens the same port on every node, forwarding to the Service | Simple external access, on-prem, or as a building block for external LBs |
| LoadBalancer | Outside, via a cloud load balancer IP or DNS | cloud-controller-manager provisions an L4 LB (AWS NLB, GCP, Azure LB) targeting nodes or pods | Exposing one service directly, often non-HTTP TCP or UDP |
| ExternalName | Inside | DNS CNAME to an external hostname | Giving an external database or API a cluster-local name |
Headless (clusterIP: None) | Inside | DNS returns individual pod IPs, no virtual IP | StatefulSets, client-side load balancing, peer discovery (kafka-0.kafka) |
An Ingress is an L7 (HTTP) routing object: host- and path-based rules ("api.example.com/orders → orders Service, /users → users Service"), TLS termination, and sometimes rewrites, auth or rate limits. An Ingress does nothing by itself. An Ingress controller implements it, for example ingress-nginx, Traefik, HAProxy, the AWS Load Balancer Controller (provisioning an ALB), or GKE Ingress. Typically, one cloud load balancer fronts the controller, which fans out to many Services. That's cheaper and simpler than one LoadBalancer Service per service.
The Gateway API (GA since 2023) is the successor to Ingress. It has role-oriented resources: GatewayClass and Gateway are owned by the platform team, and HTTPRoute, GRPCRoute and TCPRoute by app teams. It has richer matching (headers, methods), traffic splitting by weight (canaries), cross-namespace routing, and portable support across implementations: Envoy Gateway, Istio, Cilium, NGINX, and cloud gateways.
Services and Ingress, in depth: the packet path, traffic policies and service meshes#
How a ClusterIP works. A ClusterIP isn't bound to any interface. It is a rule.
- In iptables mode, kube-proxy installs NAT rules on every node. A packet to
10.96.12.7:80is DNAT-ed to a randomly chosen ready pod IP, using probability-weighted rules. Rule chains grow linearly with the number of Services and endpoints, so clusters with tens of thousands of Services see slow rule updates. - IPVS mode uses kernel hash tables, with real load-balancing algorithms.
- eBPF dataplanes (Cilium) replace kube-proxy entirely, doing lookups in eBPF maps at socket or packet level, with lower latency and better scale.
Load balancing is per connection, not per request. A long-lived HTTP/2 or gRPC connection sticks to one pod, which leaves the load uneven. Fix it with client-side load balancing, through headless Services and gRPC's round-robin over DNS, or with an L7 proxy or mesh that balances per request.
External traffic policy. For NodePort and LoadBalancer Services:
externalTrafficPolicy: Cluster(the default) lets any node accept the traffic, and forward it to a pod on another node. That spreads load evenly, but it adds a hop, and source-NATs the client IP away.externalTrafficPolicy: Localkeeps traffic on nodes that host a ready pod. That preserves the client IP and avoids the extra hop, but load can be uneven, and the LB must health-check nodes. Cloud LBs in "IP target" mode (the AWS Load Balancer Controller with VPC CNI) skip nodes, and target pod IPs directly.
Service mesh. Istio, Linkerd and Cilium Service Mesh inject a proxy (Envoy, or linkerd2-proxy) beside every pod as a sidecar, or run per-node proxies in Istio's newer "ambient" mode. These proxies give:
- mTLS between all services, with workload identities;
- per-request L7 load balancing;
- retries, timeouts and circuit breaking (Resilience Patterns);
- traffic splitting for canaries;
- authorization policies;
- uniform RED metrics and tracing for every service, with no code changes (Observability).
The costs: extra latency per hop, typically around a millisecond or less at p50, though more under load; the proxies' CPU and memory; and real operational complexity. Adopt a mesh when you have many services and need zero-trust mTLS or fine traffic control, not by default.
Cluster DNS at scale. Every service call starts with a DNS lookup. With the default ndots:5 in pods' resolv.conf, a lookup of api.stripe.com first tries several cluster search domains, multiplying queries. Use fully qualified names with a trailing dot, lower ndots, or run NodeLocal DNSCache to cut latency, and avoid overloading CoreDNS, a common hidden bottleneck.
Autoscaling: HPA, VPA and the cluster autoscaler#
Kubernetes scales at two levels: pods, to match application load, and nodes, to give the pods room.
The Horizontal Pod Autoscaler (HPA) changes a Deployment's replica count, based on metrics. Every 15 seconds by default, it computes:
desiredReplicas = ceil(currentReplicas × currentMetricValue / targetMetricValue)
For example, 6 pods at 90% average CPU, against a 60% target, gives ceil(6 × 90 / 60) = 9 pods. Metrics can be:
- resource metrics (CPU or memory utilisation relative to requests), from metrics-server;
- custom metrics (requests per second per pod, queue depth per worker), through a Prometheus adapter;
- external metrics (SQS queue length, Kafka consumer lag).
Scale-down uses a stabilisation window, 5 minutes by default, so brief dips don't cause flapping. behavior policies cap how fast it scales up or down, for example "at most double every 60 s".
KEDA (Kubernetes Event-Driven Autoscaling) extends the HPA with dozens of event sources: Kafka lag, RabbitMQ, SQS, Redis lists, cron schedules and Prometheus queries. It can scale to zero when there's no work. It's ideal for queue workers.
The Vertical Pod Autoscaler (VPA) recommends, or automatically sets, a pod's CPU and memory requests, from observed usage. It's useful for right-sizing, but in auto mode it applies changes by recreating pods, and it conflicts with an HPA that scales on the same CPU metric. Many teams run VPA in recommendation-only mode, and apply the suggestions through code review. Newer Kubernetes versions support in-place pod resizing, which reduces the restart problem.
The Cluster Autoscaler (CA) adds nodes when pods are Pending because no node can fit them. It simulates which node group would fit them, and grows that group (an AWS Auto Scaling group, a GKE node pool). It removes nodes that are under-utilised (say, under 50% of requests) for about 10 minutes, if their pods can move elsewhere, respecting PDBs. Karpenter, created by AWS and now a Kubernetes SIG Autoscaling project, is an alternative. It provisions right-sized instances directly from the pending pods' needs (choosing instance type, size, zone, and spot or on-demand), often within a minute, and consolidates nodes to cut cost.
Autoscaling, in depth: reaction time, headroom and scaling on the right signal#
End-to-end scale-up latency adds up:
- metric collection lag, 15–60 seconds;
- the HPA sync interval, 15 seconds;
- pod scheduling;
- image pull, 0 to tens of seconds;
- application startup, from about 1 second for Go to 30–90 seconds for large JVM apps;
- readiness.
If new nodes are needed, add VM boot and join: about 1–3 minutes. That's 2–5 minutes in total, which is far too slow for a sudden 5× spike. Mitigations:
- Headroom: target 60–70% utilisation, not 90%.
- Overprovisioning: low-priority placeholder pods reserve capacity, and are pre-empted instantly when real pods need room, so new pods skip node provisioning.
- Scheduled scaling before known peaks, using KEDA cron or scheduled HPA minimums.
- Faster starts: small images, pre-pulled base layers, and lazy initialisation.
- Load shedding and queues to bridge the gap (Resilience Patterns).
Choose the right signal.
- CPU works for CPU-bound stateless services.
- For I/O-bound services, CPU stays low while latency climbs. Scale on requests per second per pod, or on concurrency.
- For queue workers, scale on backlog per worker, or on expected time to drain. For example, 120,000 messages at 200 messages/s per worker, with a 60-second drain target, needs 120,000 / (200 × 60) = 10 workers.
- Never scale on latency alone. If latency is high because the database is saturated, adding pods makes it worse.
Put a maximum on every HPA, sized to what downstream dependencies (databases, third-party rate limits) can handle, and to your budget.
Requests drive everything. The HPA's CPU utilisation is relative to requests. The scheduler packs by requests. The cluster autoscaler adds nodes for requests. If requests are wrong, all three misbehave. Requests that are too high waste money, because nodes are "full" while idle. Requests that are too low cause noisy-neighbour contention and evictions. Right-size from observed p95 usage (VPA recommendations, or tools like Goldilocks), and revisit after big changes.
Bin-packing and cost. Cloud cost is nodes, not pods. Kubernetes' value often comes from packing many services densely. Typical clusters waste a great deal through over-requested resources, and cluster-level allocation of 30–50% is commonly reported. Levers:
- right-sizing requests;
- consolidating with Karpenter or CA;
- spot or preemptible instances for fault-tolerant workloads, often 60–90% cheaper, with 2-minute reclaim notices on AWS;
- ARM nodes;
- separating node pools for workloads with distinct shapes, such as GPU or memory-heavy work.
Config and secrets#
The twelve-factor principle is to keep configuration out of the image, so the same image runs in every environment. Kubernetes provides two objects.
- ConfigMap: non-sensitive key-value configuration (feature toggles, URLs, log levels, whole config files).
- Secret: sensitive values (passwords, API tokens, TLS certificates). They're stored separately, with tighter RBAC, and they can be kept in memory (tmpfs) on nodes.
Both can be consumed as environment variables or as files in a mounted volume. Mounted files update automatically when the object changes, after a short delay, so apps can reload without restarting. Environment variables are fixed at container start, and they leak more easily, into crash dumps, child processes and kubectl describe output. Prefer files for secrets. To roll pods on a config change, many teams put a hash of the config in a pod annotation, so a change triggers a rolling update. That makes config changes visible and reversible, like code.
A Kubernetes Secret is not encrypted by default. Secret values are only Base64-encoded in the API (encoding, not encryption; see Security Fundamentals). They're stored in etcd in plaintext unless you enable encryption at rest with a KMS provider: an EncryptionConfiguration using the cloud KMS, which managed clusters offer as an option. Anyone with get secrets RBAC permission in a namespace, or who can create pods there that mount secrets, can read them. Production practice:
- Enable etcd encryption with KMS (envelope encryption).
- Keep secrets out of Git. Use the External Secrets Operator, which syncs from AWS Secrets Manager, GCP Secret Manager, Vault or Azure Key Vault into Kubernetes Secrets; the Secrets Store CSI Driver, which mounts secrets from the external store directly as files; Vault Agent injection; or Sealed Secrets and SOPS, with values encrypted in Git that only the cluster can decrypt.
- Use workload identity (IRSA or EKS Pod Identity, GKE Workload Identity, Azure Workload Identity), so pods get short-lived cloud credentials tied to their service account, and no static cloud keys exist at all.
- Use tight RBAC: app service accounts shouldn't be able to list secrets, and humans get production secret access just in time.
Config and secrets, in depth: configuration drift, reload strategies and environment promotion#
Configuration as code. Store manifests in Git, and template them with Helm (charts with values per environment) or Kustomize (a base plus overlays, patching without templates). Apply them through GitOps (Argo CD, Flux), so the cluster state always matches a reviewed commit, and drift is detected and reverted (CI/CD and Deployment). Promote the same image digest through dev, staging and prod, changing only the configuration overlay.
Reload strategies.
- Restart on change: a config hash annotation, or a tool like Stakater Reloader, triggers a rolling update. It's predictable, gradual, and easy to roll back.
- Hot reload: the app watches the mounted file, and reloads in process. That's fast, but every pod changes at once, so a bad config hits everyone together.
- A dynamic config service or feature-flag platform, for runtime toggles with percentage rollouts.
Treat config changes as risky as code changes: they're a leading cause of outages. Roll them out gradually, with validation (schemas, dry-runs) in CI.
Immutable ConfigMaps and Secrets (immutable: true) can't be changed, only replaced under a new name. That protects against accidental edits, and reduces API-server watch load in big clusters.
Size limits. A ConfigMap or Secret is limited to 1 MiB, because it lives in etcd. Large files, such as ML models or big datasets, belong in object storage or volumes, not in ConfigMaps.
Kubernetes patterns: sidecar, init and ambassador#
Because a pod groups containers that share network and storage, you can compose behaviour without changing the application. The pod-level patterns were described by Burns and Oppenheimer ("Design Patterns for Container-based Distributed Systems", USENIX HotCloud 2016). They are expanded in Ibryam and Huß's book Kubernetes Patterns.
-
Sidecar: a helper container that runs alongside the main container for the pod's whole life, extending it. Examples:
- a log shipper reading the app's log files;
- a service-mesh proxy (Envoy) handling mTLS, retries and metrics;
- a Vault agent refreshing secrets into a shared volume;
- a Git-sync container refreshing static content;
- a Cloud SQL Auth Proxy.
Kubernetes added native sidecars in 1.28, on by default from 1.29. These are init containers with
restartPolicy: Always, which start before, and stop after, the main container. That fixes old ordering problems, such as a proxy not being ready when the app starts, or a sidecar keeping a Job from completing. -
Init container: runs to completion before the app containers start. It runs sequentially, and the pod waits until it succeeds. Examples: wait for a dependency to be reachable, run schema migrations (with care, as discussed below), download a model or assets into a shared volume, set kernel parameters or file permissions, render config templates. Init containers can hold tools and permissions that the app container shouldn't have.
-
Ambassador: a proxy container that represents an external service to the app, which simply talks to
localhost. The ambassador handles discovery, connection pooling, sharding, TLS, auth or retries. Examples: a Redis or Memcached sharding proxy (twemproxy), a database connection proxy (Cloud SQL Auth Proxy, PgBouncer), or a local egress proxy to third-party APIs. -
Adapter: the reverse of an ambassador. It presents the app's output in a standard format to the outside world. For example, a Prometheus exporter translates a legacy app's stats endpoint into
/metrics, or a log adapter normalises formats.
Kubernetes patterns, in depth: the wider pattern catalogue and when patterns become anti-patterns#
Beyond the pod patterns, a commonly cited "top 10" of Kubernetes design patterns adds these:
- Health probe: the app exposes liveness, readiness and startup endpoints, so the platform can manage it.
- Predictable demands: declare resource requests, limits and dependencies, so the scheduler can place pods well.
- Declarative deployment: rolling, blue-green and canary through controllers, not scripts.
- Automated placement: use node selectors, affinity and anti-affinity, taints and tolerations, and topology spread, to control where pods run. Examples: GPU pods only on GPU nodes, replicas across zones, a noisy batch job kept away from latency-critical services.
- Singleton service: exactly one active instance, either through
replicas: 1(with downtime on failure) or through leader election among replicas, using a KubernetesLeaseobject, as the control-plane components themselves do. - Stateful service: StatefulSets with stable identity and storage, usually wrapped by an operator.
- Service discovery: Services, DNS and headless Services.
- Batch job and periodic job: Jobs and CronJobs, with retries and concurrency control.
- Operator: CRDs plus a custom controller, encoding day-2 operations such as backups, failover and upgrades.
Sidecar costs at scale. A mesh sidecar per pod, at say 50–100 MiB of memory and 0.05–0.1 vCPU, across 10,000 pods, is 0.5–1 TB of RAM, and hundreds of cores, just for proxies. That's why node-level proxies (Istio ambient's ztunnel, Cilium's eBPF dataplane) and proxyless gRPC have gained ground. Sidecars also complicate pod startup, termination and resource accounting. Use them for cross-cutting concerns that must be uniform, not as a dumping ground.
Init-container migrations are a trap at scale. If every replica's init container runs migrate, then 50 pods race to change the schema on each rollout. Run migrations once, as a separate Job (a Helm hook or an Argo CD sync wave) before the rollout, and make them backward compatible, so old and new pods both work during the rolling update (the expand and contract pattern).
Storage in brief. Pods are ephemeral, so durable data uses PersistentVolumes (PVs), which are claimed through PersistentVolumeClaims (PVCs). They're provisioned dynamically by a StorageClass (EBS gp3, GCE PD, Azure Disk, Ceph). Block volumes are usually zonal: a pod with an EBS volume in eu-west-1a can only be rescheduled within that zone. That's why StatefulSets need replicas in each zone, with replication at the application level, as databases and Kafka do. Use volumeBindingMode: WaitForFirstConsumer, so a volume is created in the zone where the pod is scheduled.
Namespaces, RBAC and policies. Namespaces partition a cluster for teams or environments, with ResourceQuotas (caps on total CPU, memory and objects per namespace), LimitRanges (default requests and limits), RBAC Roles and RoleBindings (who can do what, where), NetworkPolicies (default-deny, then allow specific pod-to-pod flows), and Pod Security Admission (the "restricted" level forbids privileged, root and host-namespace pods). Namespaces are soft multi-tenancy. They share the kernel, nodes and control plane, so hostile tenants need separate node pools, sandboxed runtimes or separate clusters.
Everyday kubectl, the commands you'll actually use:
kubectl get pods -n payments -o wideshows pods and their nodes, anddescribe pod Xshows events: scheduling failures, image pull errors, probe failures, OOM kills.logs X -c app --previousshows logs from the crashed container instance.exec -it X -- shopens a shell, though distroless images have none, so usekubectl debugwith an ephemeral debug container.rollout status,rollout historyandrollout undo deploy/checkoutmanage rollouts.top podsandtop nodesshow live usage, from metrics-server.port-forward svc/checkout 8080:80gives local access.apply -f,diff -fandexplain deployment.spec.strategywork with manifests.
The common pod failure states are CrashLoopBackOff (the app keeps exiting; read the previous logs), ImagePullBackOff (a wrong image name or tag, or registry authentication), Pending (no node fits: check requests, taints, quotas, PVC zone), OOMKilled (memory limit too low, or a leak), and CreateContainerConfigError (a missing ConfigMap or Secret).
When to Use It#
Use containers almost always. Packaging services as OCI images is cheap and portable, and it's the input to nearly every modern platform: Kubernetes, ECS, Cloud Run, Fly.io, App Runner, even Lambda container images. The question is mostly where to run them. Signals that Kubernetes is worth its cost:
- Many services and teams: roughly 10–20 or more services, and several teams who benefit from one standard platform for deploys, scaling, networking, config and observability. Kubernetes becomes the organisation's internal platform.
- A mix of workload types: stateless APIs, workers, cron jobs, stateful systems through operators, GPU jobs. Kubernetes handles them all through one API.
- Portability or hybrid needs: the same deployment model across AWS, GCP, Azure and on-prem. This is common in regulated industries, or for vendors shipping to customers' clusters.
- High utilisation matters: a large fleet where bin-packing, spot instances and autoscaling save significant money.
- Ecosystem needs: service mesh, GitOps, policy engines, operators for databases and Kafka, and progressive delivery, all integrating through the same API.
- A platform team exists, or you use a managed control plane (EKS, GKE, AKS), and have at least some engineers who understand it deeply.
When NOT to Use It#
Kubernetes is a distributed system that you have to operate. Its learning curve and day-2 work (upgrades every few months, CNI and ingress choices, RBAC, policies, cost control, debugging networking) are real. Avoid it, or postpone it, when:
- You have a few services and a small team. A monolith, or 3–5 services, run more simply on a PaaS or serverless containers: Cloud Run, AWS App Runner, ECS on Fargate, Azure Container Apps, Heroku, Render or Fly.io. You get deploys, TLS, autoscaling (often to zero) and logs, without running a cluster.
- Workloads are event-driven and bursty. Functions (Lambda, Cloud Functions) or scale-to-zero containers cost nothing when idle, and need no capacity planning.
- You have nobody to own it. An unmaintained cluster drifts out of support (each Kubernetes minor version gets about 14 months of upstream patches), accumulates vulnerable add-ons, and fails at the worst time.
- The work is mostly stateful and critical, such as your primary database. Managed databases (RDS, Cloud SQL, Aurora, DynamoDB) usually beat running Postgres on Kubernetes yourself, unless you have strong operator expertise and a reason to do it.
- You need hard multi-tenant isolation for untrusted code, and can't invest in sandboxed runtimes and per-tenant node pools. Per-tenant VMs or microVM platforms are simpler and safer.
- Latency-critical or hardware-tuned systems, such as high-frequency trading or specialised appliances, gain little from the abstraction, and may suffer from its networking layers.
- "Resume-driven" adoption. Kubernetes doesn't make an app scalable or reliable by itself. Stateless design, good probes, graceful shutdown, and capacity planning do.
A reasonable path: start with a managed container platform, then move to managed Kubernetes when the number of services, teams, or workload variety makes a standard platform pay off.
How to Implement It#
- Containerise well. Use multi-stage Dockerfiles, small base images, non-root users, one process per container, stdout logging,
SIGTERMhandling, health endpoints, and config from the environment or files. Build in CI with BuildKit cache, scan, generate SBOMs, sign, and push to a regional registry. Deploy by digest. - Choose a managed control plane (EKS, GKE, AKS) unless you have strong reasons not to. Spread nodes over 3 zones, in separate node pools for system add-ons, general workloads, and special hardware.
- Lay out the cluster foundations: a CNI (the cloud VPC CNI or Cilium), an ingress or Gateway controller, cert-manager, ExternalDNS, metrics-server, a cluster autoscaler or Karpenter, an observability stack (Prometheus or OTel, logs), External Secrets or a CSI secrets store, and a policy engine (Kyverno or Gatekeeper) enforcing Pod Security "restricted", signed images, and required requests and limits.
- Establish multi-tenancy: namespaces per team and environment, RBAC tied to SSO groups, ResourceQuotas and LimitRanges, default-deny NetworkPolicies, and workload identity per service account.
- Standardise workload templates (Helm charts or Kustomize bases): Deployment with probes, resources, spread constraints, a PDB, an HPA, a Service and an HTTPRoute, plus ServiceMonitor or OTel annotations. Most teams should only fill in values.
- Deliver through GitOps: CI builds the image and updates the manifest repo, and Argo CD or Flux syncs it to clusters. Use progressive delivery (Argo Rollouts or Flagger) for critical services.
- Autoscale on the right signals: HPA on CPU or RPS, KEDA for queues, with sensible minimums and maximums, and node autoscaling with headroom.
- Operate: plan control-plane and node upgrades every quarter (with PDBs and surge upgrades), back up etcd (or rely on the managed provider) and cluster resources (Velero), keep cost dashboards per namespace (OpenCost or Kubecost), and run game days for node, zone and control-plane failures.
An HPA scaling on CPU, with controlled behaviour, plus a PDB:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: { name: checkout }
spec:
scaleTargetRef: { apiVersion: apps/v1, kind: Deployment, name: checkout }
minReplicas: 6 # survive a zone loss at peak
maxReplicas: 60 # sized to DB connection limits
metrics:
- type: Resource
resource: { name: cpu, target: { type: Utilization, averageUtilization: 60 } }
behavior:
scaleUp: { policies: [{ type: Percent, value: 100, periodSeconds: 60 }] }
scaleDown: { stabilizationWindowSeconds: 300,
policies: [{ type: Percent, value: 20, periodSeconds: 60 }] }
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: { name: checkout }
spec:
maxUnavailable: 1
selector: { matchLabels: { app: checkout } }| Technology | Fits when |
|---|---|
| Docker / BuildKit / Buildah / ko | Building OCI images; ko and Jib for Go and Java without a Dockerfile |
| containerd / CRI-O | Kubernetes node runtimes |
| EKS / GKE / AKS | Managed Kubernetes control planes on AWS, Google Cloud and Azure; GKE Autopilot and EKS Auto Mode manage nodes too |
| k3s / kind / minikube | Lightweight clusters for edge, CI and local development |
| OpenShift / Rancher | Enterprise distributions with built-in security, UI and multi-cluster management |
| ECS + Fargate / Cloud Run / Azure Container Apps | Running containers without operating Kubernetes; scale to zero on Cloud Run and Container Apps |
| Helm / Kustomize | Packaging and templating manifests across environments |
| Argo CD / Flux | GitOps continuous delivery to clusters |
| Argo Rollouts / Flagger | Canary and blue-green with automated metric analysis |
| Karpenter / Cluster Autoscaler | Node autoscaling; Karpenter for fast, flexible instance selection |
| KEDA | Event-driven pod autoscaling, scale to zero |
| Cilium / Calico | CNI with NetworkPolicy; Cilium adds eBPF dataplane and observability |
| Istio / Linkerd | Service mesh: mTLS, L7 traffic control, telemetry |
| ingress-nginx / Envoy Gateway / Traefik | Ingress and Gateway API controllers |
| External Secrets Operator / Secrets Store CSI / Vault | Injecting secrets from external stores |
| Kyverno / OPA Gatekeeper | Admission policies: security baselines, required labels, signed images |
| Velero | Backup and restore of cluster resources and volumes |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| VMs only | Strong isolation; simple mental model; any OS | Slow provisioning; low density; config drift without images | Legacy apps, strong isolation needs, few large services |
| Containers on a PaaS or serverless (Cloud Run, Fargate) | No cluster to operate; scale to zero; fast start | Less control (networking, sidecars, GPUs); platform limits; can cost more at steady high load | Small to mid teams, few services, bursty traffic |
| Managed Kubernetes | Standard platform, huge ecosystem, portability, bin-packing | Steep learning curve; add-ons, upgrades and security are still on you | Many services and teams, mixed workloads, platform team |
| Self-managed Kubernetes | Full control, on-prem or air-gapped | You run etcd, the control plane and upgrades; high skill needed | On-prem, sovereignty, very large or specialised fleets |
| Rolling update | No extra capacity; default; simple | Two versions live at once; slower rollback | Most stateless services |
| Blue-green | Instant switch and rollback | Double capacity during switch | Critical services, risky releases |
| Canary (mesh or Gateway) | Limits blast radius; metric-driven | Needs traffic-splitting tooling and good SLIs | High-traffic services with clear SLOs |
| Sidecar mesh | mTLS, retries and telemetry uniformly | CPU and memory per pod; latency; complexity | Many services needing zero trust and traffic control |
| No mesh (library-based) | Lean, simpler debugging | Inconsistent per language; app changes needed | Few services, single language |
| Secrets as Kubernetes Secrets (KMS-encrypted) | Native, simple consumption | Lives in etcd; RBAC must be tight | Most apps, with External Secrets as source of truth |
| Secrets via CSI from Vault or cloud store | Never stored in etcd; rotation from source | Extra components; pod start depends on the store | High-sensitivity secrets, compliance |
Common Pitfalls#
- No resource requests, or wildly wrong ones. The scheduler overpacks nodes, pods get OOM-killed or throttled, and HPA and CA decisions become meaningless.
- Liveness probes that check dependencies, causing cluster-wide restart storms when a database blips. Or no readiness probe, so traffic hits pods that aren't ready.
- No graceful shutdown: no
preStopdelay, and noSIGTERMhandling, so every deploy drops requests. :latesttags, or reused mutable tags. You can't tell what's running, and rollbacks don't roll anything back.- Single replica, or all replicas in one zone or node. No PDBs, so node upgrades take services down.
- Secrets in plain manifests in Git, or believing Base64 Secrets are encrypted. etcd encryption isn't enabled.
- Running as root, privileged containers, hostPath mounts, or mounting the Docker socket: trivial container escape.
- No NetworkPolicies: every pod can reach every other pod, and the cloud metadata endpoint.
- Cardinality and log floods from many pods, with no limits. Observability costs explode (Observability).
- Treating Kubernetes as the fix for an app that isn't cloud-native. Sticky local state, long startup and no horizontal scaling stay broken on Kubernetes.
- Skipping upgrades until the version is out of support, then facing many breaking API removals at once.
- One giant cluster for everything. One bad admission webhook, CRD or control-plane overload takes out every team. Prefer several clusters, by environment, region or criticality.
- HPA with no maximum, scaling into a database's connection limit, and taking down the database.
Real-World Examples#
- Google ran containers internally on Borg for over a decade before open-sourcing Kubernetes (2014), as described in the Borg (EuroSys 2015) and "Borg, Omega, and Kubernetes" (Burns, Grant, Oppenheimer, Brewer and Wilkes, ACM Queue, 2016) papers. Much of Kubernetes' design (pods, labels, controllers, the declarative API) comes from those lessons.
- Spotify migrated from its in-house orchestrator, Helios, to Kubernetes. It is also the origin of Backstage, a developer portal now widely used on top of Kubernetes platforms.
- OpenAI has written about scaling Kubernetes clusters to 7,500 nodes for research workloads (2021), including etcd and API-server tuning, and the networking choices it made.
- Airbnb, Pinterest, Shopify and many others run large Kubernetes fleets, and have published talks on multi-cluster management, autoscaling and cost.
- AWS Lambda and Fargate run customer code in Firecracker microVMs: container-like speed, with VM isolation for multi-tenant code (NSDI 2020).
- The dockershim removal (Kubernetes 1.24, 2022) moved the ecosystem to containerd and CRI-O. Docker-built OCI images were unaffected, which shows the value of the OCI standards.
- Amazon Prime Video's 2023 write-up about moving a monitoring tool from serverless functions to a single containerised process on ECS is a common reminder that the runtime platform should follow the workload's shape, not fashion.
Case studies that use this pattern#
- Code Judge (LeetCode): sandboxed containers (gVisor or Firecracker) for untrusted code, resource limits, job queues with KEDA-style autoscaling.
- Job Scheduler: Jobs and CronJobs, workers scaling on queue depth, leader election for the scheduler.
- Web Crawler: horizontally scaled fetcher workers, autoscaling on frontier backlog, spot nodes.
- ChatGPT-style Assistant: GPU node pools, scheduling and autoscaling of inference servers.
- Video Streaming: batch transcoding Jobs on spot capacity, stateless edge-facing services.
In the Interview#
Deep Dive: Scheduling, bin-packing and QoS under pressureShow
The scheduling framework. For each pending pod, the scheduler runs plugin phases.
- PreFilter and Filter exclude infeasible nodes. A node is infeasible if:
- free allocatable CPU or memory is below the pod's requests;
- the node has taints the pod doesn't tolerate;
- node selectors or affinity don't match;
- a volume's zone doesn't match the node's;
- ports conflict;
- the topology spread would be violated.
- Score ranks the feasible nodes. Plugins favour balanced allocation, image locality and spreading, and
NodeResourcesFitcan be configured asLeastAllocated(spread) orMostAllocated(pack, for cost). - Reserve, Permit and Bind finish the placement.
For large clusters, the scheduler only scores a sample of feasible nodes (percentageOfNodesToScore), trading optimality for throughput, which can reach hundreds of pods per second. If nothing fits, preemption may evict lower-PriorityClass pods to make room. That's how overprovisioning placeholder pods work.
Bin-packing is NP-hard, and schedulers use greedy heuristics. Fragmentation is real. A node might have 3 free CPUs and 1 GiB free, while the pending pod needs 1 CPU and 4 GiB. Consolidation (Karpenter, or the descheduler) periodically repacks pods onto fewer nodes, respecting PDBs. Pod shapes that match instance shapes (for example, a memory-to-CPU ratio of 4 GiB per vCPU on general-purpose instances) waste less.
Allocatable vs capacity. A node's allocatable resources are its capacity minus system and kubelet reservations, minus the eviction threshold. On small nodes, DaemonSets (log agent, CNI, exporters, mesh) can take 10–20% of the node. Bigger nodes amortise that overhead, but increase the blast radius when one fails. A common middle ground is 8–32 vCPU nodes, for general workloads.
QoS and eviction.
- Guaranteed: requests equal limits for CPU and memory, in every container.
- Burstable: requests set, but lower than limits.
- BestEffort: nothing set.
Under node memory pressure, the kubelet evicts BestEffort pods first, then Burstable pods using more than they requested, and Guaranteed pods last. Memory is incompressible: exceeding a limit means an OOM kill. CPU is compressible: over its limit it is throttled, under CFS quota periods of 100 ms. A latency-sensitive service with a CPU limit of 1 core that bursts to 4 threads can use its 100 ms quota in 25 ms, then sit throttled for 75 ms. That shows up as mysterious p99 spikes. That's why many teams drop CPU limits for latency-critical services, and rely on requests for fairness.
Worked capacity example. A service needs 3,000 RPS at peak. Each pod handles 250 RPS at the 60% CPU target, with a 1-vCPU request. That's 12 pods at peak. To survive losing one of 3 zones, it needs 12 / (2/3) = 18 pods spread across zones, and an HPA minimum of perhaps 9 at off-peak. On 16-vCPU nodes with about 14.5 vCPU allocatable, after DaemonSets, 18 pods use about 1.25 nodes of capacity. With other services sharing the nodes, bin-packing makes this cheap, which is the economic case for a shared platform.
Deep Dive: Cluster topology, multi-tenancy and the networking modelShow
One cluster or many? A cluster is a failure domain, and an upgrade unit. Common topologies:
- per environment: dev, staging, prod;
- per region: prod-eu-west-1, prod-us-east-1;
- per criticality tier, so payments is isolated from internal tools;
- sometimes per large team or tenant.
The trade-off is isolation and blast radius against operational overhead and fragmentation. Multi-cluster tools handle the overhead:
- GitOps fleets (Argo CD ApplicationSets);
- cluster API provisioning;
- multi-cluster Services (the MCS API, Cilium ClusterMesh, Istio multi-cluster);
- global load balancing across regional clusters, using the DNS or anycast patterns from High Availability Design.
Cell architecture on Kubernetes. Some companies run many identical clusters as cells, each serving a shard of customers, so that one bad deploy or a cluster failure affects only that cell's customers. Rollouts proceed cell by cell, with bake time between cells.
Multi-tenancy spectrum.
- Namespace per team, sharing nodes. This is soft isolation, with RBAC, quotas, NetworkPolicies and Pod Security.
- Dedicated node pools per tenant, using taints and affinity, so a noisy or compromised workload can't share a kernel.
- Sandboxed runtimes (gVisor, Kata) for untrusted code.
- Virtual clusters (vcluster), which give tenants their own API servers on shared nodes.
- Separate clusters, for the strongest isolation.
Choose by trust level. Internal teams usually get namespaces. Customer-supplied code gets sandboxes or separate clusters.
The networking model. Kubernetes requires that every pod gets a unique, routable IP, and that pods can reach each other without NAT. CNIs meet this in two ways.
- Overlay networks (VXLAN or Geneve encapsulation, as in Flannel, or Calico in overlay mode) work anywhere, but add encapsulation overhead.
- Native VPC routing (the AWS VPC CNI gives pods real VPC IPs; GKE uses alias IP ranges) has no overlay overhead, and pods are directly addressable by cloud load balancers. The catch is that pods consume VPC IP addresses. A /16 VPC has about 65,000 addresses, and with dozens of IPs per node, large clusters exhaust subnets. Plan CIDRs early, or use prefix delegation or secondary CIDRs.
NetworkPolicy semantics. Pods are non-isolated by default. Once any policy selects a pod for ingress, only explicitly allowed traffic gets in. Start with namespace-wide default-deny for ingress, and for egress where practical. Then allow specific flows by pod labels and namespaces, plus DNS egress to CoreDNS. Remember that egress to the cloud metadata IP (169.254.169.254) should be blocked for most pods. Cilium adds L7-aware policies (HTTP methods and paths, Kafka topics) and DNS-aware egress (toFQDNs), and Hubble shows the actual flows for debugging.
Deep Dive: Control loops, consistency and why Kubernetes is built this wayShow
Declarative, level-triggered control. The Borg, Omega and Kubernetes paper describes the shift from imperative orchestration ("start 3 tasks on machines A, B and C") to declarative desired state, plus independent controllers. Each controller is small, owns one concern, and continuously reconciles. This design has properties worth knowing.
- Robustness to failure. A controller that crashes mid-operation simply restarts, re-reads the current state, and continues. There's no lost "event" to replay, because it acts on levels (state), not edges (changes).
- Composability. Controllers coordinate only through objects in the API. The Deployment controller doesn't call the ReplicaSet controller; it writes a ReplicaSet object. New behaviour is added by adding controllers and CRDs, not by changing a central orchestrator.
- Eventual convergence. The system is eventually consistent with the desired state. There are windows where reality lags, such as pods still starting, or endpoints still propagating to nodes. Applications must tolerate this, which is why readiness, preStop delays and retries matter.
Optimistic concurrency. Every object has a resourceVersion, from etcd's revision. Updates carry it, and conflicting writes fail with 409 Conflict. The controller re-reads and retries. That avoids distributed locks for most coordination. Server-side apply tracks which manager owns each field, so GitOps tools, HPAs and humans can share an object without overwriting each other. For example, the HPA owns spec.replicas, and Git owns the rest.
Leader election. Controllers running with several replicas, for availability, elect a single active leader through a Lease object. The leader renews the lease every few seconds, and standbys take over when it expires. This relies on etcd's linearisable compare-and-swap (ZooKeeper and etcd). The same primitive is available to your own apps, for singleton work.
Watch semantics and scale. The API server serves watches from an in-memory watch cache, so thousands of kubelets and controllers don't hit etcd directly. If a watcher falls too far behind (its resourceVersion is compacted), it gets 410 Gone, and must re-list. Re-lists across a huge cluster are expensive, which is why bookmarks, consistent reads from the cache, and streaming lists were added to reduce the cost. Understanding this helps explain control-plane incidents: a mass reconnect after an API-server restart can cause a "thundering herd" of re-lists. API Priority and Fairness, and client-side backoff, are the defences, the same ideas as in Resilience Patterns.
Key Takeaways#
- Containers are isolated processes sharing the host kernel, through namespaces, cgroups and overlay filesystems. They are lighter and faster than VMs, and less isolated, so sandbox untrusted code with gVisor, Kata or Firecracker. In the cloud, containers usually run inside VMs.
- Images are stacks of content-addressed, cached layers. Use multi-stage builds, small non-root images, layers ordered for caching, no secrets in layers, scanning and signing, and deploy by digest.
- Kubernetes keeps declared state true through control loops. The API server and etcd store state, the scheduler places pods, controllers reconcile, and kubelets run pods on nodes. Existing pods survive a control-plane outage.
- Deployments run stateless pods with rolling updates gated by readiness probes. Set requests and limits, graceful shutdown, zone spreading and PDBs. Use StatefulSets, DaemonSets and Jobs for other shapes.
- Services give stable virtual IPs and DNS. ClusterIP is internal, NodePort opens node ports, LoadBalancer provisions a cloud LB, and Ingress or the Gateway API does L7 host and path routing behind one LB.
- Autoscaling: the HPA scales pods on CPU or custom metrics, KEDA on events, VPA right-sizes, and the cluster autoscaler or Karpenter adds nodes. Keep headroom, because scale-up takes minutes. Cap maximums to protect dependencies.
- Config belongs in ConfigMaps, and Secrets are Base64, not encrypted. Enable etcd KMS encryption, source secrets from Vault or a cloud manager, and use workload identity.
- Pod patterns: sidecar extends the app, init prepares it, ambassador proxies outbound dependencies, adapter standardises output. Mind the sidecar costs at scale.
- Don't use Kubernetes by default. For a few services or a small team, serverless containers or a PaaS are simpler. Adopt managed Kubernetes when many services, teams and workload types justify a shared platform, and someone owns it.