InfrastructureVol. 6 · Part VI
0 / 0

Shelves / Infrastructure

IN·83

Kubernetes

Kubernetes from first principles to advanced operation: declarative desired state and reconciliation, the control plane (API server, etcd, scheduler, controllers) and nodes (kubelet, CRI, CNI, kube-proxy), the API object model, pods (init and sidecar containers, lifecycle, termination), workloads (Deployment, ReplicaSet, StatefulSet, DaemonSet, Job, CronJob), configuration and secrets, Services, DNS, Ingress and the Gateway API, probes, resources and QoS, autoscaling (HPA, VPA, cluster autoscaling, KEDA), storage (PV, PVC, StorageClass, CSI), scheduling (affinity, taints, topology spread, priority, disruption budgets), security (RBAC, service accounts, Pod Security, network policies, admission), extension with CRDs and operators, service mesh and GitOps, with client code in Go, Java, Rust and Python.

48 topics · ~40 min read · 36-question quiz
Updated Suggest a correction

Start here: telling a cluster what you want

Desired state, not commands

With Docker you say do this: run this container, now. With Kubernetes you say I want this: three copies of this container, with these limits, reachable at this name. Controllers inside the cluster then work continuously to make reality match, and to keep it matching when things change. That's the core idea: declarative desired state plus reconciliation loops.

Here's the desired state for the menu service, as a manifest:

YAML
apiVersion: apps/v1
kind: Deployment
metadata:
  name: menu
spec:
  replicas: 3                          # desired state: three copies
  selector:
    matchLabels: { app: menu }
  template:                            # the pod template every copy is made from
    metadata:
      labels: { app: menu }
    spec:
      containers:
        - name: tiffin
          image: tiffin:2.1
          env: [{ name: VERSION, value: "menu-v1" }]
          ports: [{ containerPort: 8080 }]
          resources:
            requests: { cpu: 50m, memory: 32Mi }   # what the scheduler reserves
            limits:   { memory: 64Mi }             # the cgroup limit
          readinessProbe:                           # only send traffic when this passes
            httpGet: { path: /healthz, port: 8080 }
            periodSeconds: 2
          livenessProbe:                            # restart the container if this keeps failing
            httpGet: { path: /healthz, port: 8080 }
            periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
  name: menu
spec:
  selector: { app: menu }              # every Ready pod with this label
  ports: [{ port: 80, targetPort: 8080 }]
Text
$ kubectl apply -f tiffin.yaml
deployment.apps/menu created
service/menu created
deployment "menu" successfully rolled out
$ kubectl get deploy menu; kubectl get pods -l app=menu -o wide; kubectl get svc menu
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
menu   3/3     3            3           2s
NAME                    READY  STATUS   RESTARTS  IP
menu-5c865cb57d-pgrl8   1/1    Running  0         10.42.0.93
menu-5c865cb57d-prsk5   1/1    Running  0         10.42.0.92
menu-5c865cb57d-slsl6   1/1    Running  0         10.42.0.94
NAME   TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
menu   ClusterIP   10.43.69.144   <none>        80/TCP    2s

Each pod got its own IP address; the Service got one stable virtual IP and a DNS name, menu. From another pod in the cluster:

Text
$ wget -qO- http://menu/   (three times, from a pod in the cluster)
{"hostname":"menu-5c865cb57d-slsl6",…}
{"hostname":"menu-5c865cb57d-pgrl8",…}
{"hostname":"menu-5c865cb57d-prsk5",…}

Reconciliation in action

Text
$ kubectl delete pod/menu-5c865cb57d-pgrl8   # a pod disappears
back to 3 ready pods after 1.2 s:
menu-5c865cb57d-prsk5   1/1   Running   5s
menu-5c865cb57d-slsl6   1/1   Running   5s
menu-5c865cb57d-vkkmv   1/1   Running   1s
$ kubectl scale deploy/menu --replicas=5
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
menu   5/5     5            5           6s

Nobody told Kubernetes to replace the deleted pod. The Deployment's ReplicaSet controller saw 2 pods where 3 were desired and created one; the scheduler picked a node; the node's kubelet started the container and, once the readiness probe passed, the Service started sending it traffic. Scaling is the same loop with a new number. The same reconciliation restarts crashed containers, moves pods off failed nodes and rolls out new versions (chapter 84).

The pieces

Component Job
API server The front door: validates and stores every object; everything talks to it
etcd The cluster's database (chapter 72's Raft store)
Scheduler Chooses a node for each new pod, from requests, affinity and taints
Controller manager Runs reconciliation loops: Deployments, ReplicaSets, Nodes, Jobs, endpoints…
kubelet (each node) Starts and watches the node's pods through the container runtime; runs probes
kube-proxy / CNI (each node) Implements Services (iptables, IPVS, nftables or eBPF) and pod networking
CoreDNS Resolves Service names like menu and menu.default.svc.cluster.local

How deep to go in Kubernetes

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain pods, Deployments, Services, desired state and the main components
L2 Write manifests with resources, probes, config and secrets; use kubectl to deploy and inspect
L3 Explain scheduling, the controller pattern, Service networking, storage and RBAC
L4 Diagnose Pending, CrashLoopBackOff, OOMKilled, probe failures, DNS and networking issues
L5 Design cluster tenancy, resource policies, autoscaling, security and GitOps for a platform
L6 Operate clusters at scale: upgrades, control-plane health, multi-cluster, cost and policy

The idea

Desired state and reconciliation

Kubernetes (from Google's Borg and Omega experience; open-sourced 2014; CNCF's first graduated project) is a system for running containerised workloads across a cluster of machines. Its core idea fits in one sentence:

You declare the desired state as API objects; controllers continuously observe the actual state and act to make it match.

You don't say "start 3 containers on nodes A, B and C". You submit "a Deployment named orders with 3 replicas of image X", and a chain of controllers creates ReplicaSets, Pods, schedules them, starts containers, and keeps doing so: if a node dies, its pods are replaced elsewhere without anyone issuing a command. This reconciliation loop (observe, diff, act, repeat) is the pattern behind every part of Kubernetes, and behind the operators you can write yourself.

API server + etcdspec (desired) · status (actual) ① observe (watch) ② diffwant 3 · have 2 ③ actcreate 1 pod ④ update status
The reconciliation loop. A controller watches desired state (spec) and actual state (status) through the API server, computes the difference, and takes actions that move the world toward the spec; it repeats forever, so failures are corrected automatically.

Consequences of this design:

  • Level-triggered, not edge-triggered: controllers act on the current difference, not on missed events, so they recover from crashes and dropped notifications by simply re-reading state.
  • Eventually consistent: after kubectl apply, things converge over seconds; kubectl rollout status and kubectl wait observe convergence.
  • Everything is an API object stored in etcd, so tools (kubectl, Helm, Argo CD, Terraform, your code) all work the same way.

Architecture

control plane kube-apiserver etcd (Raft) scheduler controller-manager cloud-controller-mgr kubectl / CI / Argo node 1 node 2 kubelet containerd (CRI) kube-proxy / eBPF CNI plugin pods kubelet containerd (CRI) kube-proxy / eBPF CNI plugin pods
Kubernetes architecture. The control plane runs the API server (the only component that talks to etcd), the scheduler and controller managers. Each worker node runs the kubelet, a container runtime via CRI, kube-proxy (or an eBPF replacement) and a CNI plugin; all components communicate through the API server.

Control plane

Component Role
kube-apiserver The front door: a REST API (JSON/YAML, protobuf internally) that authenticates, authorises and runs admission on every request, validates objects, and persists them in etcd. Supports watch streams so clients get changes pushed. Stateless and horizontally scalable. Every other component talks only to the API server, never to each other directly
etcd Consistent key-value store (Raft, Vol. 5 ch. 72) holding all cluster state. Losing etcd means losing the cluster's memory: back it up (etcdctl snapshot save)
kube-scheduler Watches for pods without a node, filters nodes that can run them (resources, taints, affinity, volumes), scores the rest, and binds the pod to the best node
kube-controller-manager Runs built-in controllers: Deployment, ReplicaSet, StatefulSet, DaemonSet, Job, CronJob, Node (detects dead nodes), EndpointSlice, ServiceAccount, namespace deletion, garbage collection (owner references)
cloud-controller-manager Cloud-specific controllers: creates cloud load balancers for LoadBalancer Services, manages node lifecycle and routes

Control planes run with 3+ API servers and a 3- or 5-member etcd cluster for availability. Managed services (EKS, GKE, AKS, DigitalOcean, OKE, and others) run the control plane for you; you manage nodes (or not, with GKE Autopilot, EKS Auto Mode, AKS Automatic, or Fargate).

Nodes

Component Role
kubelet The node agent: watches the API server for pods bound to its node, asks the runtime to run their containers, mounts volumes, runs probes, reports pod and node status, enforces resource limits via cgroups, evicts pods under node pressure
Container runtime containerd or CRI-O, called through the CRI (gRPC), using runc/crun (chapter 80)
kube-proxy Programs Service virtual IPs into the kernel (iptables or nftables mode, the future default; IPVS mode is deprecated); or replaced entirely by an eBPF datapath (Cilium)
CNI plugin Gives each pod an IP and connectivity (chapter 80)

Talking to the API

Every object has the same shape:

YAML
apiVersion: apps/v1          # API group/version
kind: Deployment             # type
metadata:
  name: orders
  namespace: shop
  labels: { app: orders, team: checkout }      # identifying, used by selectors
  annotations: { owner: "checkout@acme.dev" }  # non-identifying metadata
spec: { … }                  # desired state (you write)
status: { … }                # observed state (controllers write)
  • Labels and selectors are how objects find each other: a Service selects pods by app: orders; a Deployment manages pods matching its selector. There are no hard links between them, only label queries.
  • Namespaces partition names, RBAC, quotas and policies (shop, payments, monitoring). They aren't a security boundary on their own; combine them with RBAC, network policies and quotas.
  • Owner references link created objects to their owner (Pod → ReplicaSet → Deployment); deleting the owner garbage-collects dependants.
  • Declarative management: keep YAML in Git and kubectl apply -f (or better, server-side apply: kubectl apply --server-side, which tracks field ownership per manager). Avoid imperative kubectl edit in production; it drifts from Git.
Shell
kubectl get pods -n shop -o wide            # list
kubectl describe pod orders-7d9f-abc -n shop   # events, conditions, why it isn't starting
kubectl logs -f deploy/orders -n shop --all-containers
kubectl get events -n shop --sort-by=.lastTimestamp
kubectl explain deployment.spec.strategy    # built-in API documentation
kubectl get deploy orders -o yaml           # (kubectl 1.37: -o kyaml for a stricter YAML dialect)
kubectl api-resources                       # every kind the cluster knows, including CRDs

Pods

The smallest unit

A Pod is one or more containers that are scheduled together onto one node and share:

  • a network namespace: one IP, one port space; containers talk over localhost;
  • volumes declared in the pod spec;
  • optionally a PID namespace (shareProcessNamespace: true);
  • lifecycle: they're created and destroyed together.

Pods are ephemeral and disposable: they don't move or get repaired. When a node dies, its pods are gone, and controllers create new pods (new names, new IPs) elsewhere. So you almost never create bare pods; you create workloads that manage them.

Init and sidecar containers

  • Init containers run to completion, in order, before the app containers start: wait for a dependency, run migrations (carefully), fetch config, set permissions on a volume.
  • Sidecar containers (native support GA since 1.33) are init containers with restartPolicy: Always: they start before the app containers, keep running alongside them, and are stopped after them. Uses: log shippers, service-mesh proxies, secret refreshers, Cloud SQL proxy. Native sidecars fixed old problems (Jobs that never finished because the sidecar kept running; app starting before the proxy was ready).

Lifecycle and termination

Pod phases: Pending (accepted, not yet running: scheduling, image pull), Running, Succeeded, Failed, Unknown. Container states: Waiting (with reasons like ContainerCreating, ImagePullBackOff, CrashLoopBackOff), Running, Terminated (with exit code and reason, such as OOMKilled). restartPolicy: Always (default for long-running), OnFailure, Never (Jobs).

CrashLoopBackOff means the container keeps exiting and the kubelet restarts it with exponential back-off (10 s, 20 s, 40 s… up to 5 minutes). Look at kubectl logs --previous and describe.

Termination is where many production bugs hide:

time → (terminationGracePeriodSeconds, default 30 s) delete endpoints path removed from EndpointSlice proxies/LBs update (seconds)… kubelet path preStop (sleep) SIGTERM drain in-flight, exit 0 SIGKILL preStop delay lets endpoint removal propagate before the app stops accepting connections
Pod termination sequence. When a pod is deleted, two things happen in parallel: it's removed from Service endpoints (which takes time to propagate to every proxy), and the kubelet runs the preStop hook then sends SIGTERM. The app must keep serving briefly, drain, and exit before the grace period ends, or it's SIGKILLed.
  1. The pod is marked terminating. Two things start in parallel: it's removed from Service endpoints, and the kubelet starts shutdown.
  2. The kubelet runs the preStop hook (if any), then sends SIGTERM to each container's PID 1.
  3. After terminationGracePeriodSeconds (default 30), anything still running gets SIGKILL.

Because endpoint removal propagates asynchronously to kube-proxy on every node, ingress controllers and load balancers, a pod can still receive new requests for a few seconds after SIGTERM. If the app stops listening immediately, those requests fail with connection errors during every rollout. The standard fix: a short preStop sleep (Kubernetes 1.30+ has a native sleep action, no shell needed), then graceful shutdown on SIGTERM (chapter 79), with the grace period longer than both.

YAML
lifecycle:
  preStop:
    sleep: { seconds: 5 }               # let endpoint removal propagate
terminationGracePeriodSeconds: 40       # > preStop + app drain time

Workloads

Deployment and ReplicaSet

A ReplicaSet keeps N identical pods running (matching its selector). A Deployment manages ReplicaSets to provide declarative updates: changing the pod template creates a new ReplicaSet and shifts pods from old to new according to the strategy (RollingUpdate with maxSurge/maxUnavailable, or Recreate; chapter 84). Old ReplicaSets are kept (scaled to 0) for rollback (revisionHistoryLimit).

YAML
apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders
  namespace: shop
  labels: { app.kubernetes.io/name: orders }
spec:
  replicas: 3
  revisionHistoryLimit: 5
  selector:
    matchLabels: { app.kubernetes.io/name: orders }
  strategy:
    type: RollingUpdate
    rollingUpdate: { maxSurge: 25%, maxUnavailable: 0 }
  template:
    metadata:
      labels: { app.kubernetes.io/name: orders }
    spec:
      serviceAccountName: orders
      automountServiceAccountToken: false
      securityContext:
        runAsNonRoot: true
        runAsUser: 10001
        fsGroup: 10001
        seccompProfile: { type: RuntimeDefault }
      containers:
      - name: orders
        image: ghcr.io/acme/orders:1.4.2@sha256:3b1c…   # pinned by digest
        ports: [{ name: http, containerPort: 8080 }]
        env:
        - { name: JAVA_TOOL_OPTIONS, value: "-XX:MaxRAMPercentage=75" }
        - name: DB_PASSWORD
          valueFrom: { secretKeyRef: { name: orders-db, key: password } }
        envFrom: [{ configMapRef: { name: orders-config } }]
        resources:
          requests: { cpu: 500m, memory: 768Mi }
          limits:   { memory: 768Mi }                    # memory limit; no CPU limit (see below)
        startupProbe:
          httpGet: { path: /actuator/health/liveness, port: http }
          periodSeconds: 5
          failureThreshold: 24                           # up to 2 minutes to start
        readinessProbe:
          httpGet: { path: /actuator/health/readiness, port: http }
          periodSeconds: 5
        livenessProbe:
          httpGet: { path: /actuator/health/liveness, port: http }
          periodSeconds: 10
          failureThreshold: 3
        lifecycle:
          preStop: { sleep: { seconds: 5 } }
        securityContext:
          allowPrivilegeEscalation: false
          readOnlyRootFilesystem: true
          capabilities: { drop: [ALL] }
        volumeMounts: [{ name: tmp, mountPath: /tmp }]
      volumes:
      - { name: tmp, emptyDir: {} }
      terminationGracePeriodSeconds: 40
      topologySpreadConstraints:
      - maxSkew: 1
        topologyKey: topology.kubernetes.io/zone
        whenUnsatisfiable: ScheduleAnyway
        labelSelector: { matchLabels: { app.kubernetes.io/name: orders } }

StatefulSet

For workloads whose instances need stable identity: databases, Kafka, ZooKeeper/etcd, Elasticsearch.

  • Pods get stable, ordinal names (kafka-0, kafka-1, kafka-2) and stable DNS via a headless Service (kafka-0.kafka.shop.svc.cluster.local).
  • Each pod gets its own PersistentVolumeClaim from volumeClaimTemplates, which follows the pod identity across rescheduling (data-kafka-0 always mounts on kafka-0).
  • Ordered creation, scaling and rolling updates by default (podManagementPolicy: OrderedReady; Parallel is available), and partition for staged updates.
  • Kubernetes only gives identity and storage; the application must handle clustering, replication and failover. That's why databases on Kubernetes are usually run by operators (CloudNativePG, Strimzi for Kafka, the MongoDB and MySQL operators, Vitess, CockroachDB, ECK for Elasticsearch).

DaemonSet, Job, CronJob

  • DaemonSet: one pod per node (or per matching node): log collectors (Fluent Bit), node exporters, CNI agents, CSI node plugins, security agents. New nodes get one automatically.
  • Job: runs pods to completion: completions, parallelism, backoffLimit, activeDeadlineSeconds, ttlSecondsAfterFinished (clean up), indexed jobs (each pod gets an index for sharded work), podFailurePolicy (don't retry on certain exit codes), successPolicy.
  • CronJob: creates Jobs on a cron schedule, with timeZone, concurrencyPolicy (Allow, Forbid, Replace), startingDeadlineSeconds, and history limits. Jobs must be idempotent: a CronJob can occasionally run twice or be skipped.
YAML
apiVersion: batch/v1
kind: CronJob
metadata: { name: nightly-reconcile, namespace: shop }
spec:
  schedule: "15 3 * * *"
  timeZone: "Asia/Kolkata"
  concurrencyPolicy: Forbid
  jobTemplate:
    spec:
      backoffLimit: 2
      activeDeadlineSeconds: 3600
      ttlSecondsAfterFinished: 86400
      template:
        spec:
          restartPolicy: Never
          containers:
          - name: reconcile
            image: ghcr.io/acme/reconciler:2.1.0
            args: ["--date", "yesterday"]

Configuration and secrets

  • ConfigMap: non-sensitive configuration (key/value pairs or whole files). Consumed as environment variables (read once at start) or as mounted files (updated in place eventually, about a minute later, except with subPath mounts). Many teams roll pods on config change by hashing the ConfigMap into a pod annotation (Helm, Kustomize configMapGenerator).
  • Secret: the same mechanics for sensitive data. Important: Secret values are only base64-encoded, not encrypted. Protect them with:
  • encryption at rest in etcd (KMS provider);
  • RBAC limiting get/list on Secrets (anyone who can create a pod in a namespace can mount its Secrets);
  • mounting as files rather than env vars;
  • external secret stores via the External Secrets Operator (syncs from AWS Secrets Manager, GCP Secret Manager, Vault, Azure Key Vault) or the Secrets Store CSI Driver;
  • Sealed Secrets or SOPS for storing encrypted secrets in Git.
  • Downward API: expose pod metadata (name, namespace, labels, resource limits) to the container as env vars or files.
  • Immutable ConfigMaps/Secrets (immutable: true) reduce API server load and prevent accidental changes.

Services and networking

Services

Pods come and go with changing IPs. A Service gives a stable virtual IP and DNS name in front of a set of pods selected by labels. The EndpointSlice controller tracks which pod IPs are currently ready; kube-proxy (or eBPF) programs every node so traffic to the Service IP is load-balanced to those endpoints.

Type Exposure
ClusterIP (default) Virtual IP reachable only inside the cluster
Headless (clusterIP: None) No virtual IP; DNS returns the pod IPs directly (StatefulSets, client-side balancing, gRPC)
NodePort Opens a port (30000–32767) on every node, forwarding to the Service
LoadBalancer Asks the cloud (via cloud-controller-manager or a controller like AWS Load Balancer Controller, MetalLB on bare metal) for an external L4 load balancer
ExternalName DNS CNAME to an external name
YAML
apiVersion: v1
kind: Service
metadata: { name: orders, namespace: shop }
spec:
  selector: { app.kubernetes.io/name: orders }
  ports: [{ name: http, port: 80, targetPort: http }]
  trafficDistribution: PreferClose    # prefer same-zone endpoints (saves cross-zone cost/latency)

Only ready pods (readiness probe passing) are in the endpoints, which is why readiness matters so much.

DNS

CoreDNS serves cluster DNS: orders.shop.svc.cluster.local resolves to the ClusterIP; inside namespace shop, just orders works. Pods' /etc/resolv.conf contains search domains and ndots:5: any name with fewer than five dots is first tried with each search suffix, so api.stripe.com triggers several failed lookups before the real one. For heavy external lookups, use fully qualified names with a trailing dot (api.stripe.com.) or lower ndots via dnsConfig; run NodeLocal DNSCache in large clusters.

Ingress and Gateway API

To expose HTTP services externally:

  • Ingress: host/path rules → Services, implemented by an Ingress controller. Features beyond basic routing depend on controller-specific annotations. The widely used community Ingress NGINX controller was retired in March 2026.
  • Gateway API (GA core since v1.0, 2023): the successor, with role separation and portable features:
YAML
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata: { name: public, namespace: infra }
spec:
  gatewayClassName: envoy            # or istio, cilium, nginx, gke-l7-global-external-managed…
  listeners:
  - name: https
    protocol: HTTPS
    port: 443
    hostname: "*.example.com"
    tls: { certificateRefs: [{ name: wildcard-example-com }] }
    allowedRoutes: { namespaces: { from: All } }
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata: { name: orders, namespace: shop }
spec:
  parentRefs: [{ name: public, namespace: infra }]
  hostnames: ["api.example.com"]
  rules:
  - matches: [{ path: { type: PathPrefix, value: /orders } }]
    backendRefs:
    - { name: orders, port: 80, weight: 95 }
    - { name: orders-canary, port: 80, weight: 5 }     # traffic splitting in the spec
    timeouts: { request: 10s }

cert-manager issues and renews certificates (ACME, internal CAs) as Secrets referenced by Gateways or Ingresses.

Network policies

By default, every pod can talk to every pod. A NetworkPolicy selects pods and restricts ingress and/or egress; once a pod is selected by any policy for a direction, only explicitly allowed traffic passes. Enforcement requires a CNI that supports it (Calico, Cilium; many cloud CNIs). Start with default deny per namespace and allow what's needed:

YAML
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: default-deny, namespace: shop }
spec:
  podSelector: {}                         # all pods in the namespace
  policyTypes: [Ingress, Egress]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: orders-allow, namespace: shop }
spec:
  podSelector: { matchLabels: { app.kubernetes.io/name: orders } }
  policyTypes: [Ingress, Egress]
  ingress:
  - from: [{ namespaceSelector: { matchLabels: { kubernetes.io/metadata.name: infra } } }]
    ports: [{ port: 8080 }]
  egress:
  - to: [{ podSelector: { matchLabels: { app.kubernetes.io/name: postgres } } }]
    ports: [{ port: 5432 }]
  - to: [{ namespaceSelector: {}, podSelector: { matchLabels: { k8s-app: kube-dns } } }]
    ports: [{ port: 53, protocol: UDP }, { port: 53, protocol: TCP }]   # don't forget DNS

Cilium and Calico add richer policies (L7 HTTP rules, DNS-name-based egress, cluster-wide policies); the upstream AdminNetworkPolicy API adds cluster-admin-level policies.

Health checks

Kubernetes has three probes with different consequences:

Probe Question On failure Typical check
startupProbe "Has the app finished starting?" Keep waiting (up to failureThreshold × periodSeconds), then kill and restart Same endpoint as liveness, with a generous budget
readinessProbe "Should this pod receive traffic right now?" Removed from Service endpoints (not restarted) Can serve: initialised, warm, not overloaded; maybe critical local dependencies
livenessProbe "Is the process wedged beyond self-recovery?" Container restarted Process responsive (event loop not stuck, no deadlock); never downstream dependencies

Probe types: httpGet, tcpSocket, exec, grpc. Parameters: initialDelaySeconds, periodSeconds, timeoutSeconds, failureThreshold, successThreshold.

Rules that prevent outages:

  • Don't check databases or other services in liveness. If the database is down, every pod fails liveness, Kubernetes restarts all of them, and the restart storm makes recovery slower: a cascading failure (Vol. 5 ch. 78).
  • Liveness should be cheap and local; readiness may reflect the ability to serve.
  • Use a startupProbe for slow starters (JVM warm-up, cache loading) instead of a huge initialDelaySeconds on liveness.
  • During shutdown, readiness should fail (many frameworks do this automatically on SIGTERM).
  • Framework support: Spring Boot Actuator /actuator/health/liveness and /readiness (enabled automatically on Kubernetes); Quarkus SmallRye Health /q/health/live and /ready; Micronaut; ASP.NET Core health checks; Go and Rust typically expose /livez and /readyz handlers; the gRPC health checking protocol for grpc probes.

Resources

Requests and limits

Each container declares:

  • Requests: what the scheduler reserves on a node (cpu: 500m = half a core; memory: 768Mi). A pod only lands on a node with enough unreserved capacity. Requests also set the CPU weight under contention.
  • Limits: the cgroup caps enforced by the kernel. CPU limit → throttling (cpu.max); memory limit → OOM kill (OOMKilled, exit 137).

QoS classes

Class Condition Eviction order under node pressure
Guaranteed Every container has requests = limits for CPU and memory Last
Burstable Some requests or limits set, not all equal Middle (by usage above request)
BestEffort No requests or limits at all First

Practical guidance

  • Always set memory requests and limits, usually equal (memory isn't compressible; overcommitting it leads to OOM kills or node-pressure evictions at bad moments).
  • Set CPU requests realistically (from observed usage, p90–p95). CPU limits are debated: they cause throttling and latency spikes even when the node has idle CPU (chapter 80), so many teams omit CPU limits for latency-sensitive services and rely on requests for fair sharing. Keep limits where you need strict isolation or predictable billing.
  • Size runtimes to limits: -XX:MaxRAMPercentage, GOMEMLIMIT, worker counts.
  • In-place pod resize (GA in 1.35) changes CPU and memory of running pods without restarting them (kubectl patch … --subresource resize), with per-resource resizePolicy (e.g. memory changes may still require a restart for some runtimes). Pod-level resources (GA in 1.37) let you set a budget for the whole pod that containers share.
  • LimitRange sets per-namespace defaults and bounds; ResourceQuota caps a namespace's total requests, limits and object counts (multi-tenant fairness).

Scaling

Horizontal Pod Autoscaler

The HPA adjusts a workload's replica count from metrics:

desiredReplicas = ceil( currentReplicas × currentMetricValue / targetValue )

  • Metrics: resource (CPU/memory utilisation relative to requests, from metrics-server), custom (requests per second, queue length via Prometheus Adapter), external (cloud queue depth).
  • behavior controls scale-up and scale-down speed and stabilisation windows (default scale-down window 5 minutes to avoid flapping); a per-HPA tolerance (GA in 1.37) replaces the global ±10% dead band.
  • CPU-based HPA only works if requests are set and representative; it reacts in tens of seconds to minutes, so keep headroom for spikes.
YAML
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: { name: orders, namespace: shop }
spec:
  scaleTargetRef: { apiVersion: apps/v1, kind: Deployment, name: orders }
  minReplicas: 3
  maxReplicas: 30
  metrics:
  - type: Resource
    resource: { name: cpu, target: { type: Utilization, averageUtilization: 65 } }
  behavior:
    scaleUp:   { stabilizationWindowSeconds: 0,   policies: [{ type: Percent, value: 100, periodSeconds: 30 }] }
    scaleDown: { stabilizationWindowSeconds: 300, policies: [{ type: Percent, value: 20,  periodSeconds: 60 }] }

KEDA

KEDA (Kubernetes Event-Driven Autoscaling, CNCF graduated) scales on event sources: Kafka consumer lag, SQS/RabbitMQ queue length, Prometheus queries, cron schedules, and more (70+ scalers), including scale to zero for idle consumers. It creates and drives HPAs under the hood.

Vertical Pod Autoscaler

The VPA (an add-on) recommends or sets requests from observed usage. Modes: Off (recommendations only, a safe way to right-size), Initial (only at pod creation), Recreate, and InPlaceOrRecreate (uses in-place resize). Don't let VPA and HPA both act on the same metric (CPU) for one workload.

Cluster autoscaling

When pods are Pending because no node has room, nodes must be added; when nodes are underused, removed:

  • Cluster Autoscaler: scales cloud node groups (auto scaling groups, managed instance groups) up for unschedulable pods and down for underutilised nodes, respecting PodDisruptionBudgets.
  • Karpenter (AWS origin, now a Kubernetes SIG project with AWS and Azure providers): provisions right-sized nodes directly from pod requirements (instance type, zone, spot vs on-demand), and consolidates workloads onto fewer, cheaper nodes.
  • Node provisioning takes minutes: combine with HPA headroom, over-provisioning placeholder pods with low priority, or warm pools.

Storage

Volumes, PVs and PVCs

  • Ephemeral volumes live and die with the pod: emptyDir (scratch space, optionally RAM-backed with medium: Memory), configMap, secret, projected, downwardAPI, generic ephemeral volumes.
  • PersistentVolume (PV): a piece of storage in the cluster (a cloud disk, an NFS export, a Ceph volume), with capacity, access modes and a reclaim policy.
  • PersistentVolumeClaim (PVC): a pod's request for storage ("20 GiB, ReadWriteOnce, class fast-ssd"). The control plane binds a PVC to a matching PV.
  • StorageClass: describes a kind of storage and its provisioner; PVCs that reference it get PVs dynamically provisioned (a new EBS/PD/Azure disk created on demand).
  • CSI (Container Storage Interface): the plugin standard through which storage vendors provide drivers (AWS EBS/EFS, GCE PD, Azure Disk/Files, Ceph RBD/CephFS via Rook, Longhorn, Portworx, NetApp Trident). In-tree cloud plugins have been migrated to CSI.
podvolume: pvc PVC data-orders20Gi · RWO · fast-ssd StorageClassfast-ssd → CSI driver cloud diskvol-0abc PV pvc-7f2…→ vol-0abc binds WaitForFirstConsumer: disk created in the zone where the pod is scheduled
Dynamic provisioning. A pod references a PVC; the PVC names a StorageClass; the CSI driver for that class creates a cloud disk and a PV, which binds to the PVC; the kubelet attaches and mounts the disk into the pod on its node.
Access mode Meaning Typical backing
ReadWriteOnce (RWO) Mounted read-write by one node Block disks (EBS, PD, Azure Disk)
ReadWriteOncePod (RWOP) Read-write by one pod Same, stricter
ReadOnlyMany (ROX) Read-only by many nodes Shared filesystems, snapshots
ReadWriteMany (RWX) Read-write by many nodes NFS, EFS, Azure Files, CephFS

Key settings:

  • volumeBindingMode: WaitForFirstConsumer: delay provisioning until the pod is scheduled, so the disk is created in the pod's zone (block disks are zonal; a disk in zone A can't attach to a node in zone B).
  • Reclaim policy: Delete (default for dynamic: deleting the PVC deletes the disk!) or Retain (keep data for manual recovery). Use Retain for anything precious.
  • allowVolumeExpansion: true to grow PVCs.
  • VolumeSnapshots (CSI) for backups and cloning; volume group snapshots (GA in 1.36) for crash-consistent snapshots across several PVCs. Back up with Velero or the storage system's tools, and test restores.
  • Stateful workloads on Kubernetes are mainstream now, but operating databases still needs expertise: prefer managed databases or mature operators.

Scheduling

The scheduler filters feasible nodes, then scores them. You influence it with:

Mechanism Purpose Example
nodeSelector Simple label match disktype: ssd
Node affinity Required or preferred rules on node labels Prefer node.kubernetes.io/instance-type in (m7g.xlarge); require arm64
Pod affinity / anti-affinity Place near or away from other pods (by labels) within a topology domain Co-locate cache with app on same node; keep replicas on different nodes
Taints and tolerations Nodes repel pods unless pods tolerate the taint GPU nodes tainted nvidia.com/gpu:NoSchedule; only GPU workloads tolerate. NoExecute evicts running pods
Topology spread constraints Even spread across zones, nodes or custom domains with maxSkew Spread replicas evenly across 3 zones
PriorityClass and preemption Higher-priority pods can evict lower-priority ones when the cluster is full Critical services over batch jobs
Resource requests Bin-packing input —
DRA (Dynamic Resource Allocation) Claim specialised devices (GPUs, partitions of GPUs, network devices) with structured parameters AI/ML workloads; GA core in 1.34 with more features since
YAML
# Spread across zones; never two replicas on one node; run only on arm64 on-demand nodes
spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - { key: kubernetes.io/arch, operator: In, values: [arm64] }
          - { key: karpenter.sh/capacity-type, operator: In, values: [on-demand] }
    podAntiAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
      - topologyKey: kubernetes.io/hostname
        labelSelector: { matchLabels: { app.kubernetes.io/name: orders } }
  topologySpreadConstraints:
  - maxSkew: 1
    topologyKey: topology.kubernetes.io/zone
    whenUnsatisfiable: DoNotSchedule
    labelSelector: { matchLabels: { app.kubernetes.io/name: orders } }
  tolerations:
  - { key: dedicated, operator: Equal, value: checkout, effect: NoSchedule }

Disruptions

  • Voluntary disruptions (node drains for upgrades, autoscaler scale-down, kubectl drain) respect PodDisruptionBudgets: minAvailable: 2 or maxUnavailable: 1 for pods matching a selector. Without a PDB, a drain can take down all replicas at once.
  • Involuntary disruptions (hardware failure, kernel panic, OOM, spot reclaim) aren't covered by PDBs: survive them with replicas spread across nodes and zones.
  • Node-pressure eviction: the kubelet evicts pods when the node runs low on memory, disk or PIDs (BestEffort first).
YAML
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: { name: orders, namespace: shop }
spec:
  maxUnavailable: 1
  selector: { matchLabels: { app.kubernetes.io/name: orders } }

Security

Authentication, RBAC and service accounts

Every API request is authenticated (client certificates, OIDC tokens for humans via your identity provider, ServiceAccount tokens for workloads, cloud IAM integrations), then authorised, by default with RBAC:

  • Role (namespaced) / ClusterRole (cluster-wide): lists of verbs (get, list, watch, create, update, patch, delete) on resources in apiGroups.
  • RoleBinding / ClusterRoleBinding: grant a role to subjects (users, groups, ServiceAccounts).
  • Principle of least privilege: no wildcard verbs or resources; avoid cluster-admin bindings; list on Secrets reveals their contents; create on pods in a namespace effectively grants access to everything that namespace's pods can mount.
  • kubectl auth can-i create deployments -n shop --as system:serviceaccount:shop:ci tests permissions.

ServiceAccounts give pods an identity. Tokens are projected, short-lived and audience-bound (rotated automatically by the kubelet), not the old long-lived Secret tokens. Set automountServiceAccountToken: false for pods that don't call the API. Workload identity maps ServiceAccounts to cloud IAM roles (EKS Pod Identity / IRSA, GKE Workload Identity Federation, Azure Workload Identity), so pods access cloud services without static keys.

YAML
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata: { name: config-reader, namespace: shop }
rules:
- apiGroups: [""]
  resources: ["configmaps"]
  verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata: { name: orders-config-reader, namespace: shop }
subjects: [{ kind: ServiceAccount, name: orders, namespace: shop }]
roleRef: { apiGroup: rbac.authorization.k8s.io, kind: Role, name: config-reader }

Pod security

  • securityContext (shown in the Deployment above): runAsNonRoot, runAsUser, readOnlyRootFilesystem, allowPrivilegeEscalation: false, capabilities.drop: [ALL], seccompProfile: RuntimeDefault, and user namespaces (hostUsers: false, GA in 1.36).
  • Pod Security Standards (Privileged, Baseline, Restricted) enforced per namespace by the built-in Pod Security Admission with labels: pod-security.kubernetes.io/enforce: restricted.
  • Avoid hostNetwork, hostPID, hostPath mounts and privileged: true outside system components.

Admission control

After authorisation, admission controllers can mutate and validate objects before they're stored:

  • Built-in plugins (LimitRanger, ResourceQuota, PodSecurity, ServiceAccount, NodeRestriction).
  • ValidatingAdmissionPolicy (GA in 1.30) and MutatingAdmissionPolicy (GA in 1.36): policies written in CEL expressions, run inside the API server, with no webhook to operate.
  • Admission webhooks call your HTTPS service: policy engines Kyverno (YAML policies; can also generate and mutate resources, verify image signatures) and OPA Gatekeeper (Rego), plus image-signature verifiers (Sigstore policy-controller).

Common policies: images only from your registry and signed by CI; no latest tags; resource requests required; labels required; no privileged pods; restricted host paths.

YAML
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata: { name: require-digest-pinned-images }
spec:
  failurePolicy: Fail
  matchConstraints:
    resourceRules:
    - { apiGroups: ["apps"], apiVersions: ["v1"], operations: ["CREATE", "UPDATE"], resources: ["deployments"] }
  validations:
  - expression: "object.spec.template.spec.containers.all(c, c.image.contains('@sha256:'))"
    message: "Container images must be pinned by digest."

(A ValidatingAdmissionPolicyBinding applies the policy to selected namespaces.)

Extending Kubernetes

CRDs and controllers

A CustomResourceDefinition adds a new kind to the API (Database, KafkaTopic, Certificate), with OpenAPI schema validation, versions and status subresources. The API server stores and serves custom objects like built-in ones; a controller you write reconciles them.

An operator is a controller that encodes operational knowledge for a specific application: creating a PostgreSQL cluster, configuring replication, taking backups, performing failover and version upgrades. Mature examples: CloudNativePG, Strimzi (Kafka), cert-manager, Prometheus Operator, Crossplane (cloud resources as Kubernetes objects), Argo CD.

The reconcile function is the whole programming model: given the current custom resource, make the world match, and report status. It must be idempotent (it runs many times for the same state), level-based, and use owner references so children are garbage-collected.

// Go: controller-runtime (kubebuilder / Operator SDK), reconcile a "Website" CR into a Deployment
func (r *WebsiteReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    var site webv1.Website
    if err := r.Get(ctx, req.NamespacedName, &site); err != nil {
        return ctrl.Result{}, client.IgnoreNotFound(err)       // deleted: children are GC'd via owner refs
    }
    dep := &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Name: site.Name, Namespace: site.Namespace}}
    _, err := controllerutil.CreateOrUpdate(ctx, r.Client, dep, func() error {
        dep.Spec.Replicas = ptr.To(site.Spec.Replicas)
        dep.Spec.Selector = &metav1.LabelSelector{MatchLabels: map[string]string{"site": site.Name}}
        dep.Spec.Template.Labels = map[string]string{"site": site.Name}
        dep.Spec.Template.Spec.Containers = []corev1.Container{{Name: "web", Image: site.Spec.Image}}
        return controllerutil.SetControllerReference(&site, dep, r.Scheme)   // owner reference
    })
    if err != nil { return ctrl.Result{}, err }                                // requeued with back-off
    site.Status.ReadyReplicas = dep.Status.ReadyReplicas
    return ctrl.Result{}, r.Status().Update(ctx, &site)
}

func (r *WebsiteReconciler) SetupWithManager(mgr ctrl.Manager) error {
    return ctrl.NewControllerManagedBy(mgr).For(&webv1.Website{}).Owns(&appsv1.Deployment{}).Complete(r)
}

Writing operators well is hard (status conditions, finalizers for external cleanup, rate limits, leader election, upgrades of the CRD schema, testing with envtest). Use one when you're encoding real operational logic; for simple templating, Helm or Kustomize is enough.

Service mesh and GitOps

Service mesh concepts

Chapter 82 covered meshes: in Kubernetes, Istio (sidecar or ambient mode), Linkerd, and Cilium add mTLS between pods, traffic policies (retries, timeouts, traffic splitting), authorisation policies, and uniform telemetry, increasingly configured through the Gateway API for both north-south and east-west traffic (the GAMMA initiative).

Packaging: Helm and Kustomize

  • Helm: the package manager for Kubernetes. A chart is a set of Go-templated manifests plus values.yaml; helm install/upgrade renders and applies them and tracks releases with history and rollback. Charts are distributed via OCI registries. Helm 4 (released late 2025) modernised the internals (server-side apply support, WASM plugins). Great for distributing third-party software; templated YAML can get hard to read.
  • Kustomize (built into kubectl apply -k): no templates; a base of plain YAML plus overlays that patch it per environment (dev, staging, prod), with generators for ConfigMaps/Secrets that add content hashes.
  • Alternatives: cdk8s (TypeScript, Python, Java, Go), Jsonnet/Tanka, CUE, Pulumi, Timoni.

GitOps

GitOps (Weaveworks, 2017) applies the reconciliation idea to deployment itself:

  1. The desired state of the cluster (manifests, Helm values, Kustomize overlays) lives in Git, which becomes the single source of truth and the audit log.
  2. An agent in the cluster (Argo CD or Flux, both CNCF graduated) pulls from Git and continuously reconciles the cluster to match, reporting drift and (optionally) correcting it.
  3. Changes happen by pull request: review, approval and history come for free; rollback is git revert.
app repo CIbuild · test registry config repoPR: new digest clusterArgo CD / Fluxpull · sync · drift update digest watch pull image
GitOps flow. CI builds and pushes an image, then opens a pull request updating the image digest in the config repository; once merged, Argo CD or Flux in the cluster detects the change and applies it, continuously correcting drift.

Benefits: no cluster credentials in CI (the cluster pulls), consistent multi-cluster management (Argo CD ApplicationSets), drift detection, easy disaster recovery (point a new cluster at the repo). Progressive delivery tools (Argo Rollouts, Flagger) plug in for canaries (chapter 84).

Debugging checklist

Symptom First commands Common causes
Pod Pending kubectl describe pod (Events) Insufficient CPU/memory, unsatisfiable affinity/taints, PVC not bound (zone mismatch), quota exceeded
ImagePullBackOff describe Wrong tag/digest, private registry credentials (imagePullSecrets), rate limits, architecture mismatch
CrashLoopBackOff logs --previous, describe App error on start, missing config/secret, failing liveness probe, OOMKilled
OOMKilled describe (Last State), kubectl top pod Limit too low, runtime not sized to limit, leak
Not receiving traffic kubectl get endpointslices -l kubernetes.io/service-name=orders, check readiness Readiness failing, selector/label mismatch, wrong targetPort, NetworkPolicy
Intermittent 502/503 during deploys Termination settings No preStop delay, app stops before endpoints update, no PDB/maxUnavailable 0
Slow p99, low CPU cgroup cpu.stat, metrics CPU limit throttling
DNS slowness CoreDNS metrics, ndots Search-domain expansion, CoreDNS under-provisioned
Need a shell in distroless kubectl debug -it pod/x --image=busybox --target=app Ephemeral debug container sharing the process namespace

Clients in code

// Go: client-go, list pods and watch for changes (informers cache and resync in real controllers)
cfg, _ := rest.InClusterConfig()                        // or clientcmd for kubeconfig
cs := kubernetes.NewForConfigOrDie(cfg)
pods, _ := cs.CoreV1().Pods("shop").List(ctx, metav1.ListOptions{LabelSelector: "app.kubernetes.io/name=orders"})
for _, p := range pods.Items { fmt.Println(p.Name, p.Status.Phase) }
w, _ := cs.CoreV1().Pods("shop").Watch(ctx, metav1.ListOptions{})
for ev := range w.ResultChan() { fmt.Println(ev.Type, ev.Object.(*corev1.Pod).Name) }

Lab: how Kubernetes reacts

A single-node k3s 1.37 cluster (2 vCPUs, 8 GB) on the volume's VM, the tiffin image, and an Alpine image for helper pods. On a cgroup v1 host, k3s needed --kubelet-arg=fail-cgroupv1=false: recent kubelets refuse to start on cgroup v1 by default (this 1.37 one did), and containerd 2.2 warns that v1 support will be removed by 2029. Plan new nodes on cgroup v2.

Experiment 1: CrashLoopBackOff

A container that prints starting, sleeps a second and exits with status 1:

Text
t=3s restart #1
t=18s restart #2
t=49s restart #3
crasher   0/1     Error    3 (81s ago)   100s

The kubelet restarted it after about 10 s, then waited longer each time (roughly 10, 20, 40, 80 s, capped at 5 minutes), so a broken container can't burn the node's CPU restarting. CrashLoopBackOff is the status during those waits. The cause is always in the container's own output: kubectl logs crasher --previous shows the last failed run, and kubectl describe pod shows the exit code and reason.

Experiment 2: OOMKilled

A shell trying to hold 200 MB in a pod limited to 32 MiB:

Text
phase=Failed reason=OOMKilled exitCode=137

The same cgroup OOM kill as chapter 80, now reported by Kubernetes. With a Deployment it would restart and probably loop; check kubectl describe pod for Last State: Terminated, Reason: OOMKilled and either raise the limit or bound the runtime's memory (heap settings).

Experiment 3: Pending

A pod requesting 4 CPUs on a 2-CPU node:

Text
greedy   0/1     Pending   0          4s
0/1 nodes are available: 1 Insufficient cpu. preemption: 0/1 nodes are available: 1 Preemption is not helpful for scheduling.

The scheduler compares requests (not actual usage) with each node's allocatable capacity minus other pods' requests. Nothing fits, so the pod waits; on a cloud cluster, the Cluster Autoscaler or Karpenter would add a node. Other FailedScheduling reasons you'll meet: insufficient memory, taints without tolerations, node affinity, pod anti-affinity, and unbound PersistentVolumeClaims.

Experiment 4: readiness removes a pod from a Service

Three tiffin:2.2 pods behind a Service, with a readiness probe on /readyz every second (2 failures to mark not ready). One pod's readiness is switched off through its /toggle-ready endpoint:

Text
endpoints before: web-876644bbc-bqj7x=true web-876644bbc-kfqdf=true web-876644bbc-bh5x6=true
pod web-876644bbc-bh5x6's readiness switched off; removed from the Service after 1.6 s
endpoints after:  web-876644bbc-bqj7x=true web-876644bbc-kfqdf=true web-876644bbc-bh5x6=false
30 requests through the Service afterwards:
     16 web-876644bbc-bqj7x
     14 web-876644bbc-kfqdf
the pod itself is still running: Running, restarts 0

Within two probe periods the EndpointSlice marked the pod not ready and kube-proxy stopped sending it traffic, while the container kept running (no restart). That's what readiness is for: a pod warming caches, overloaded, or shutting down can step out of rotation without being killed. Liveness probes, by contrast, restart containers, so they should check only that the process isn't hung, never its dependencies (or a database blip restarts every pod at once).

Experiment 5: what a Service is on the node

Text
iptables rules created by kube-proxy: 255 (nat rules for the menu Service: 11)
-A KUBE-SVC-WCHJKB6JOIJ6ZA7J … "default/menu -> 10.42.0.92:8080" -m statistic --mode random --probability 0.33333333349 …
-A KUBE-SVC-WCHJKB6JOIJ6ZA7J … "default/menu -> 10.42.0.94:8080" -m statistic --mode random --probability 0.50000000000 …
-A KUBE-SVC-WCHJKB6JOIJ6ZA7J … "default/menu -> 10.42.0.97:8080" -j KUBE-SEP-ZBWF3D5DHWYCBGV4

There's no process listening on the Service's virtual IP. kube-proxy wrote NAT rules: traffic to the ClusterIP jumps to a chain that picks a pod at random (one third, then half of the rest, then the last), and DNATs the connection to that pod's IP. Load is balanced per connection, not per request, so long-lived HTTP/2 or gRPC connections stick to one pod (use client-side balancing or a mesh for those). Large clusters use IPVS, nftables (GA in 1.33) or eBPF (Cilium) instead of thousands of iptables rules.

Try it yourself

  1. Add a HorizontalPodAutoscaler (kubectl autoscale deploy menu --cpu-percent=50 --min=2 --max=6) and generate CPU load; watch kubectl get hpa -w.
  2. Mount a ConfigMap and a Secret into tiffin as environment variables and as files; change the ConfigMap and see which form updates without a restart.
  3. Create a Role and RoleBinding that let a ServiceAccount only get and list pods, and test it with kubectl auth can-i --as=system:serviceaccount:default:viewer.
  4. Use kubectl debug with an ephemeral container to get a shell beside the scratch-based tiffin container.

Revision sheet: Kubernetes

Key ideas

  • Model: declarative objects stored in etcd via the API server; controllers reconcile; everything is a watch loop.
  • Architecture: API server, etcd, scheduler, controller manager, cloud controller; kubelet, container runtime (CRI), kube-proxy, CNI, CSI on nodes; CoreDNS.
  • Pods: one or more containers sharing network and volumes; init and sidecar containers; lifecycle and restart policy; probes (startup, readiness, liveness); graceful termination.
  • Workloads: Deployment/ReplicaSet, StatefulSet, DaemonSet, Job/CronJob.
  • Config: ConfigMaps, Secrets (base64, not encryption; use encryption at rest or external secret stores), environment vs mounted files.
  • Services and networking: ClusterIP, NodePort, LoadBalancer, headless; EndpointSlices; DNS; Ingress and Gateway API; NetworkPolicy.
  • Resources: requests vs limits, QoS classes, LimitRange, ResourceQuota, eviction.
  • Scaling: HPA (metrics-server, custom metrics, KEDA), VPA, Cluster Autoscaler/Karpenter.
  • Storage: PersistentVolumes and Claims, StorageClasses, CSI, access modes, StatefulSet volume templates.
  • Scheduling: node selectors, affinity/anti-affinity, taints and tolerations, topology spread, priority and preemption.
  • Security: RBAC, ServiceAccounts, Pod Security Standards, securityContext, admission (validating/mutating, Kyverno, Gatekeeper), image policy.
  • Extending: CRDs, operators, controllers with client-go/controller-runtime.

Numbers to remember

  • CrashLoopBackOff: 10 s doubling to a 5-minute cap.
  • Default termination grace period: 30 s.
  • Lab: restarts at 3 s, 18 s, 49 s; OOMKilled exit 137; Pending on "Insufficient cpu"; a not-ready pod left the Service in 1.6 s with no restart; 11 NAT rules for a 3-pod Service.

Pitfalls

  • No requests (scheduling blind) or memory limits far above requests (overcommit and evictions).
  • Liveness probes that check dependencies.
  • No readiness probe, so traffic reaches pods before they're ready.
  • Secrets treated as encrypted.
  • latest tags with IfNotPresent pull policy.
  • Long-lived connections and kube-proxy's per-connection balancing.

Glossary

  • Reconciliation: driving actual state towards desired state.
  • EndpointSlice: the list of pod addresses behind a Service.
  • QoS class: Guaranteed, Burstable or BestEffort, from requests and limits.
  • Taint / toleration: node repels pods unless they tolerate it.
  • CRD: custom resource definition extending the API.
  • Operator: a controller encoding operational knowledge for an application.