Containers & Kubernetes: How Pods Get Scheduled, Probed, Updated and Stopped


System Design Phase 14: Infrastructure & Delivery
Core Lesson 77 of 86 20 min read Updated Nov 30, 2026

It is 14:05 and the checkout service is deploying version 412. Kubernetes reports the rollout as healthy: 30 of 30 pods ready, zero restarts. Meanwhile the error dashboard shows a spike of 502s that lasts exactly as long as the rollout, about four minutes, and then vanishes. Roughly 0.8% of checkout requests failed during that window. Nobody changed any code that could return a 502.

At 16:40 a different team sees their Java service restart every 20 minutes with exit code 137. The node it runs on has 11 GiB of free memory. Their p99 latency also tripled last week after someone set a CPU limit of 1 core “for safety”, even though average CPU usage is only 40% of a core.

None of these are bugs in the application logic. They are three of the most common ways teams misunderstand the platform their code runs on: graceful shutdown, memory limits, and CPU limits. This article explains containers and Kubernetes from the kernel up, so you can predict that behaviour instead of discovering it in production.

What it is

A container is an ordinary Linux process that the kernel isolates and constrains. Isolation comes from namespaces (what the process can see) and resource control comes from cgroups (what the process can use). There is no guest operating system: every container on a host shares one kernel.

A virtual machine runs a full guest kernel on virtual hardware provided by a hypervisor. That gives stronger isolation (a kernel bug in one VM does not reach its neighbours) at the cost of a boot measured in seconds and a memory overhead measured in hundreds of MB per instance. A container starts in milliseconds because starting it is just a clone() with some extra flags.

Kubernetes is a system that keeps a cluster of machines running the set of containers you declared. You write down desired state (“30 replicas of checkout:412, each needing half a CPU”) and a set of controllers keep changing actual state until it matches. That loop, not any single feature, is the idea to hold on to.

How it works

Namespaces, cgroups v2 and images

Linux provides several namespace types and a container runtime typically uses all of them:

Namespace Isolates Why it matters
PID process IDs the app sees itself as PID 1, so it must handle signals
network interfaces, routes, ports each pod gets its own IP address
mount filesystem view the image becomes the root filesystem
UTS, IPC hostname, shared memory per-container hostname
user UID mapping root in the container can map to an unprivileged host user
cgroup cgroup tree view the container sees only its own limits

cgroups v2 is the unified hierarchy the kernel uses to account for and cap CPU, memory, I/O and process counts. Kubernetes has moved to it fully: starting with v1.35 the kubelet refuses to start on a cgroup v1 node by default, so any current node image needs a cgroup v2 kernel and distribution.

An image is a stack of read-only, content-addressed layers plus a small JSON config (entrypoint, environment, user). Each layer is a tarball identified by its SHA-256 digest, and an overlay filesystem stacks them with a thin writable layer on top. Because layers are addressed by digest, ten images built on the same base share that base on disk and in the registry, and a rebuild that only changes your application layer pushes and pulls only that layer. Order your Dockerfile from least to most frequently changing for exactly this reason.

The format is standardised by the Open Container Initiative (OCI): the image spec (layers and manifests), the runtime spec (how to run a filesystem bundle) and the distribution spec (the registry API). That is why an image built with Docker, Buildah or a CI builder runs unchanged under containerd or CRI-O. Kubernetes talks to runtimes through the Container Runtime Interface, and it removed its built-in Docker shim back in v1.24, which changed nothing for OCI images.

The control plane and the reconciliation loop

flowchart LR
U["kubectl / CI"] -->|"apply manifest"| API["API server"]
API <-->|"read / write"| ETCD["etcd<br/>(Raft, source of truth)"]
SCH["Scheduler"] -->|"watch unscheduled pods<br/>bind to node"| API
CM["Controller manager<br/>(Deployment, ReplicaSet, Job...)"] -->|"watch, create pods"| API
subgraph node["Worker node"]
  KL["kubelet"] --> CR["containerd / CRI-O"]
  KP["kube-proxy or eBPF dataplane"]
end
KL -->|"watch pods bound here<br/>report status"| API
style API fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style ETCD fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style SCH fill:#E1F5EE,stroke:#0F6E56,color:#085041
style CM fill:#E1F5EE,stroke:#0F6E56,color:#085041
style KL fill:#F1EFE8,stroke:#888780,color:#444441
  • API server: the only component that talks to etcd. Everything else, including the scheduler and the kubelets, is a client that reads and watches objects through it. It handles authentication, admission (policy checks, defaulting) and validation.
  • etcd: a small, strongly consistent key value store replicated with Raft. It needs a majority of members to accept writes, which is why control planes run 3 or 5 etcd members, a topic covered in distributed consensus.
  • Scheduler: watches for pods with no node, filters out nodes that cannot fit the pod (resources, taints, affinity, topology spread), scores the rest and writes a binding.
  • Controllers: each watches one kind of object and acts to close the gap. The Deployment controller creates ReplicaSets, the ReplicaSet controller creates pods, the node controller marks unreachable nodes.
  • kubelet: the agent on each node. It watches pods bound to its node, asks the runtime to start containers, runs probes and reports status.

Nothing calls anything directly. Every component watches the API server and reacts. Here is what happens after a deploy:

sequenceDiagram
participant CI as CI pipeline
participant API as API server + etcd
participant DC as Deployment controller
participant S as Scheduler
participant K as kubelet (node 7)
CI->>API: update Deployment image to v412
API-->>DC: watch event: spec changed
DC->>API: create new ReplicaSet, scale it up by maxSurge
API-->>S: watch event: pod has no node
S->>API: bind pod to node 7
API-->>K: watch event: pod bound to me
K->>K: pull image, start container, run probes
K->>API: status: Ready
API-->>DC: new pod ready
DC->>API: scale old ReplicaSet down by one, repeat

Because every step is “observe, compare, act”, the system is self-healing by construction. Delete a pod and the ReplicaSet controller notices 29 of 30 and creates one. Lose a node and its pods are recreated elsewhere after the node is marked unreachable. It also means changes are eventually consistent: kubectl apply returning success only means desired state was stored, not that anything is running yet.

Core objects

Object What it is for
Pod one or more containers sharing a network namespace and volumes; the unit of scheduling
Deployment stateless replicas with rolling updates, via ReplicaSets
StatefulSet stable pod names (db-0, db-1), ordered rollout, one persistent volume per replica
DaemonSet one pod per node: log shippers, CNI agents, node exporters
Job / CronJob run to completion, with retries and parallelism; on a schedule
Service a stable virtual IP and DNS name in front of the ready pods matching a label selector
Ingress / Gateway API HTTP routing from outside the cluster into Services
ConfigMap / Secret configuration and credentials injected as env vars or files

A Service does not proxy through a box. The control plane maintains EndpointSlices listing the IPs of ready pods, and each node’s dataplane (kube-proxy rules or an eBPF implementation) rewrites traffic for the Service IP to one of them. Only pods that pass their readiness probe are listed, which is what makes rolling updates safe. Cluster DNS and service-to-service traffic management are covered in service discovery and mesh.

Ingress vs Gateway API. Ingress is a single, limited resource whose real behaviour lives in controller-specific annotations. Its API is frozen. Gateway API (GA since v1.0 in 2023, v1.6 released mid 2026) splits the job into roles: a platform team owns GatewayClass and Gateway (listeners, TLS certificates), and app teams own HTTPRoute or GRPCRoute objects with header matching, rewrites and weighted backends built in. The popular ingress-nginx controller was retired in March 2026 and no longer receives security fixes, so new clusters should start on Gateway API. Weighted routing for canaries is shown in deployment strategies.

Secrets are only base64 encoded by default, which is encoding, not encryption. Turn on encryption at rest with a KMS provider, restrict who can read them with RBAC, and prefer pulling from an external secret manager. Details are in secrets management and encryption.

Requests, limits and QoS classes

Every container can declare a request and a limit for CPU and memory:

resources:
  requests:
    cpu: "500m"      # half a core, used for scheduling
    memory: "1Gi"
  limits:
    memory: "1Gi"    # hard ceiling, exceeding it gets the container killed
    # no CPU limit on purpose, see below

Requests are a scheduling promise. The scheduler places pods by summing requests against each node’s allocatable capacity. It never looks at actual usage. Under contention, CPU is shared in proportion to requests, so a pod always gets at least what it requested.

Limits are enforcement, and CPU and memory are enforced very differently:

  • CPU is compressible. A CPU limit becomes a CFS quota: with a limit of 1 core and the default 100 ms period, the container may use 100 ms of CPU time per 100 ms of wall clock across all its threads. A JVM with 8 busy GC and request threads can burn that 100 ms in 12.5 ms of wall time and then sits throttled for the remaining 87.5 ms. Average usage can read 40% while individual requests stall for tens of milliseconds. That is the second team’s tripled p99. Watch container_cpu_cfs_throttled_periods_total.
  • Memory is incompressible. The kernel cannot slow down memory use, so when a container exceeds its memory limit the kernel OOM-kills a process in it. The container exits with code 137 and restarts, regardless of how much memory the node has free. That is the first team’s restart loop: their heap plus metaspace plus thread stacks exceeded the container limit, not the node.

From requests and limits Kubernetes derives a QoS class for each pod:

QoS class Rule Under node memory pressure
Guaranteed every container has CPU and memory requests equal to limits evicted last
Burstable at least one request or limit set, not Guaranteed evicted if using more than its requests
BestEffort no requests or limits at all evicted first

A common, defensible default for latency-sensitive services: set CPU requests from measured usage, set no CPU limit, and set the memory limit equal to the memory request. Memory then behaves predictably, CPU bursts use idle capacity instead of being throttled, and requests still guarantee each pod its fair share. Use CPU limits where you need hard isolation, such as multi-tenant clusters or batch jobs that would otherwise starve neighbours.

Requests also set how full your nodes run. If you size requests at exactly average usage, every pod runs near 100% of its share and latency climbs steeply as utilisation rises. Drag the slider to see why a target around 60 to 70% leaves headroom for bursts:

Why busy servers get slow

Push utilisation from 70% to 90%, then to 99%, and watch the latency multiplier.

M/M/1 model: random (Poisson) arrivals, exponential service times, one server. Mean time in system T = S / (1 − ρ). Real traffic with burstier arrivals degrades even faster.

The same reasoning drives the Horizontal Pod Autoscaler’s target utilisation, which is measured as a percentage of requests. Scaling signals and capacity planning live in autoscaling and capacity planning.

Probes

The kubelet runs three kinds of probe, and confusing them causes outages:

  • Readiness: “should this pod receive traffic right now?” Failing removes the pod from Service endpoints without restarting it. Use it for warm-up, for temporary overload, and during shutdown.
  • Liveness: “is this process wedged beyond recovery?” Failing restarts the container. Keep it cheap and local, such as a handler that returns 200 if the event loop is responsive.
  • Startup: “has the app finished booting?” Until it succeeds, liveness and readiness are not run. Use it for slow starters instead of a huge initialDelaySeconds.

Never make a liveness probe check the database or a downstream service. If the database blips, every pod fails liveness at once and Kubernetes restarts your entire fleet, turning a 10 second dependency hiccup into a multi-minute outage with cold caches. This is the same anti-pattern as the deep health check discussed in load balancing. Dependency awareness, if you want it at all, belongs in readiness, and even there it should be applied carefully so a shared dependency cannot drain every pod simultaneously.

Rolling updates and PodDisruptionBudgets

A Deployment rolls out by creating a new ReplicaSet and shifting replicas across, bounded by two knobs: maxSurge (extra pods allowed above the desired count, default 25%) and maxUnavailable (pods allowed below it, default 25%). For a service at capacity, set maxUnavailable: 0 and a positive maxSurge so serving capacity never drops. The rollout only proceeds as new pods pass readiness, so a version that never becomes ready simply stalls instead of taking the service down. Set progressDeadlineSeconds so a stall is reported as a failure.

A PodDisruptionBudget limits voluntary disruptions that go through the eviction API: node drains during upgrades, cluster autoscaler scale-down, spot reclaim handlers. minAvailable: 90% on a 30 pod service means a drain may evict at most 3 at a time. It does not protect against node crashes, and it does not govern Deployment rollouts, which are controlled by maxSurge and maxUnavailable. Strategy choices beyond rolling updates are covered in deployment strategies and feature flags.

Graceful shutdown

Back to the 502s. When a pod is deleted, two things start in parallel: the kubelet sends SIGTERM to the container, and the control plane removes the pod from EndpointSlices, which every node’s dataplane and every external load balancer then has to pick up. The second path takes from hundreds of milliseconds to several seconds. If the app exits on SIGTERM immediately, traffic still routed to it hits a closed socket.

sequenceDiagram
participant API as API server
participant K as kubelet
participant App as App container
participant LB as Dataplane / LB
API->>K: pod marked Terminating
API->>LB: remove pod from endpoints (propagates over 1 to 5 s)
K->>App: run preStop hook (sleep 10 s)
Note over App,LB: still serving while routes converge
K->>App: SIGTERM
App->>App: stop accepting, drain in-flight, close keep-alives
App-->>K: exit 0
Note over K,App: if not exited by terminationGracePeriodSeconds (default 30 s), SIGKILL

The fix has three parts:

  1. A preStop hook that sleeps 5 to 15 seconds, so the pod keeps serving while endpoint removal propagates. SIGTERM is only sent after preStop completes.
  2. A SIGTERM handler that stops accepting new connections, finishes in-flight requests, sends Connection: close on keep-alive connections, and then exits. Your process is PID 1 in its namespace, so if a shell wrapper swallows signals, use an exec form entrypoint or a tiny init.
  3. A terminationGracePeriodSeconds larger than preStop plus your longest request. The default is 30 seconds, after which the container is SIGKILLed.

With all three, the checkout team’s deploy-time 502s go to zero. This is connection draining, the same idea a load balancer’s deregistration delay implements.

Where it breaks

  • Scheduling on requests, not usage. Pods with requests far below real usage pack too densely and then fight; pods with requests far above usage waste nodes. Measure, then set requests from the p90 to p95 of real usage.
  • Unset requests. BestEffort pods get scheduled anywhere, are evicted first, and make capacity planning impossible. Enforce defaults with a LimitRange or admission policy.
  • Runtimes that ignore the container limit. Older runtimes sized thread pools and heaps from the host’s CPU count and memory. Modern JVMs read cgroup limits and Go sets GOMAXPROCS from the CPU limit since Go 1.25, but verify that heap settings leave room for non-heap memory and that thread pools are not sized from the host core count.
  • etcd is the hard dependency. Large objects, huge numbers of watched resources or a chatty operator can push etcd latency up and slow the whole control plane. Running pods keep running when the control plane is down, but nothing can be scheduled, scaled or healed.
  • Cluster as blast radius. A bad admission webhook, CNI upgrade or cluster-wide config change can break every workload in the cluster at once. Large organisations run many smaller clusters, often aligned to cells, instead of one giant one.
  • Stateful workloads. StatefulSets give stable identity and volumes, but they do not give you backups, failover or replication. Running a database on Kubernetes is viable with a mature operator; it is not free.
  • Upgrade treadmill. Kubernetes ships three minor releases a year and each gets roughly 14 months of patch support upstream. v1.37 (August 2026) is the latest release as of November 2026. Skipping upgrades for a year leaves you on an unsupported version and facing API removals all at once.

Real-world systems

  • Amazon EKS runs the control plane for you; you choose how to provide nodes: managed node groups, Karpenter for just-in-time provisioning, Fargate profiles, or EKS Auto Mode, where AWS also manages node provisioning, OS patching and core add-ons.
  • GKE Autopilot goes furthest: Google manages nodes entirely and bills by the CPU, memory and storage your pods request rather than by node, which turns bin packing into Google’s problem. GKE Standard gives you node pools to manage yourself.
  • Azure AKS provides a managed control plane with paid tiers for an uptime SLA, plus node pools and cluster autoscaling.
  • Amazon ECS (often on Fargate) and Google Cloud Run run containers without Kubernetes at all. ECS has tasks, services and load balancer integration with much less surface area. Cloud Run takes an image and gives you an autoscaled HTTPS endpoint that scales to zero, which is covered in serverless trade-offs.

How to apply it

Is Kubernetes overkill? Kubernetes earns its keep when you run many services, need a consistent deployment and policy layer across teams, want portability across clouds or on-premises, or need fine control over scheduling (GPUs, spot capacity, topology). It costs you a platform team, an upgrade cadence and a large surface area to secure.

Situation Reasonable default
1 to 10 stateless HTTP services, one cloud, small team Cloud Run, ECS on Fargate or App Runner style services
Spiky or low traffic, event driven functions or Cloud Run, see serverless trade-offs
20+ services, several teams, shared platform managed Kubernetes (EKS, GKE, AKS)
Want Kubernetes APIs without node ops GKE Autopilot or EKS Auto Mode
Strict multi-cloud or on-premises Kubernetes with a vendor distribution

Production checklist for every workload:

  • CPU and memory requests set from measured usage; memory limit equals request; CPU limit only with a reason.
  • Readiness, liveness and (if slow to boot) startup probes, with liveness checking only the process itself.
  • preStop sleep, SIGTERM handling and a grace period longer than your longest request.
  • maxUnavailable: 0 for capacity-critical services, and a PodDisruptionBudget.
  • At least 2 replicas spread across zones with topology spread constraints.
  • Images pinned by digest or immutable tag, scanned, running as a non-root user.
  • Secrets from a secret manager, encrypted at rest, and workload identity rather than static keys, see mTLS and workload identity.

Interview questions

Q1: A pod is OOMKilled every 20 minutes, but the node has 11 GiB free. What is happening and how do you fix it?

The container exceeded its own memory limit, which is enforced per cgroup by the kernel; free memory on the node is irrelevant. Exit code 137 and reason OOMKilled confirm it. Check what is actually using memory: for a JVM, heap plus metaspace, thread stacks, direct buffers and code cache. Fix by either raising the memory limit and request to cover real peak usage with margin, or by capping the runtime (for example setting the max heap to about 70 to 75% of the container limit). If usage grows steadily until the kill, it is a leak and raising the limit only delays it. If the node itself ran out of memory, you would instead see kubelet evictions, starting with BestEffort pods.

Q2: Every deploy causes a short burst of 502 errors even though all new pods become ready. Walk through the causes.

Look at both ends of the rollout. On the new side, a missing or too-shallow readiness probe lets pods receive traffic before they can serve, and a rollout with maxUnavailable above 0 can briefly reduce capacity. On the old side, the usual cause is that SIGTERM and endpoint removal happen concurrently, so the old pod exits while load balancers and node dataplanes still route to it, or it drops in-flight and keep-alive connections. The fix is a preStop sleep long enough for endpoint removal to propagate, an app that drains on SIGTERM, a terminationGracePeriodSeconds longer than preStop plus the longest request, and maxUnavailable 0 with surge. A PodDisruptionBudget would not help here because rollouts are not governed by PDBs.

Q3: When would you advise against Kubernetes?

When the workload is a handful of stateless services on one cloud and the team cannot staff platform work. Kubernetes adds an upgrade cycle of three minor releases a year, cluster add-ons to maintain, a security surface (RBAC, admission, network policy, node patching) and a learning curve. ECS on Fargate or Cloud Run give rolling deploys, autoscaling and load balancing with far less to operate. Kubernetes becomes worth it with many services and teams, a need for a common policy and deployment layer, portability requirements, or specialised scheduling such as GPUs and spot capacity.

✅ Key takeaways

  • A container is a Linux process isolated by namespaces and constrained by cgroups v2; an OCI image is a stack of content-addressed layers. VMs isolate with a separate kernel.
  • Kubernetes is a set of controllers reconciling desired state stored in etcd through the API server. Everything watches; nothing calls directly.
  • The scheduler packs pods by requests, never usage. Memory over the limit means an OOMKill; a CPU limit means CFS throttling that can wreck tail latency.
  • Readiness gates traffic, liveness restarts wedged processes and must not check dependencies, startup protects slow boots.
  • Zero-downtime rollouts need readiness probes, maxUnavailable 0, a preStop sleep and real SIGTERM draining. PDBs protect against drains, not rollouts.
  • Kubernetes pays off with many services and teams; for a few services, Cloud Run or ECS is usually the better trade.

🧠 Check your understanding

0 / 4
  1. 1A service has CPU request 500m and CPU limit 1. Average CPU usage is 400m, yet p99 latency spikes. What is the most likely cause?

  2. 2Which probe failure removes a pod from Service endpoints without restarting it?

  3. 3During node drains for a cluster upgrade, you want at most 3 of 30 checkout pods down at once. What do you configure?

  4. 4Why add a preStop sleep of about 10 seconds to a web server pod?

Where to go next

Finished this lesson?

Mark it complete to track your progress across the roadmap.