AlgoViz

Kubernetes

medium 34 min

Kubernetes runs containers on many machines.

Video lesson · Chapter 1 of 5

A three-counter plan becomes three running processes

0:00 / 4:51

Kubernetes in 80 seconds

1:20Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A container packs a program with the files it needs (see Docker). Running one container is easy. Running hundreds on dozens of machines raises questions: which machine, what if it dies, how do callers find the copies, how do you replace a version without an outage? Software that answers these is a container orchestrator. Kubernetes, often written K8s, is the best known. It is open source under the Apache 2.0 licence.

Its central idea is desired state. You do not send orders such as "start a copy on machine 4". You store a description such as "three copies of api, version 1.0". Programs called controllers watch that description and the real world, and act whenever the two differ.

Why it exists

It automates work people used to do by hand: placing programs, restarting them, replacing a lost machine's share, rolling out versions, and adding copies under load. Because it is all described in files, changes can be reviewed, versioned and repeated.

The same description runs on AWS, Google Cloud, Azure or your own machines, and a large ecosystem builds on it: Helm, operators, service meshes such as Istio and Linkerd, Prometheus, Fluentd. Portability has edges, though: load balancers, disks, identity and node pools still differ per provider.

A short history

  1. 2014, June

    The first commit of Kubernetes lands on 6 June. The project is announced on 10 June in a keynote at DockerCon by Eric Brewer of Google. It carries over lessons from Borg, Google's internal cluster manager.

  2. 2015, July

    Version 1.0 is released on 21 July, and Google announces that the project will go to the new Cloud Native Computing Foundation.

  3. 2016 and 2018

    The foundation accepts Kubernetes on 10 March 2016. On 6 March 2018 it reaches the graduated level.

  4. 2025, November

    The project announces that the widely used Ingress NGINX controller will retire in March 2026. New work goes to the Gateway API.

  5. 2026, September

    Three minor versions are supported: 1.37, 1.36 and 1.35. Each receives about one year of patches.

Words to know

Cluster
A control plane and a set of worker machines managed together.
Node
One worker machine, virtual or physical. It runs the kubelet, a container runtime such as containerd, and usually kube-proxy.
Pod
The smallest thing you deploy: one or more containers that share an IP address and can share storage.
Controller
A loop that compares desired state with actual state and acts on the difference.
Service
A stable name and address in front of a changing set of pods.
Namespace
A named section of a cluster, used to separate teams or environments and to attach quotas and permissions.
Request and limit
What a container is promised when it is placed, and the most it may use.

How it works

Step through the idea, or press Play.

Step 1 of 3

Describe. Store the desired state through the API server

Understand it

Start here

The plan on the shed door

Picture a gardener who never tells helpers what to do. The gardener pins a plan to the shed door, and the helpers keep comparing the beds with the plan.

Three tomato plants, always
PlanTomatoes3Bed ABed B

The helpers never store the truth. The plan on the door is the truth.

The idea

What it does, and what it leaves to you

Kubernetes does

  • Place containers on machines
  • Restart, replace and reschedule them
  • Roll versions forward and back
  • Give stable names and spread traffic
  • Scale on CPU, memory or your own metrics
  • Mount storage, settings and secrets
  • Run custom resources through operators

Kubernetes does not

  • Build your code or images
  • Provide databases, queues or caches
  • Make a program safe to run twice
  • Choose your logging and monitoring
  • Make one cluster survive losing its region
  • Encrypt secrets at rest unless you switch it on

Why teams adopt it

  • Automated operations

    Placement, health checks, scaling and failover stop being manual work.

  • Self-healing

    Crashed containers restart. Pods of a dead node are replaced. The system moves towards the desired state.

  • Safe releases

    Pods are replaced gradually and a new one gets traffic only when it is ready. Going back is one command.

  • Portable description

    The same objects work on managed services and on your own machines.

Architecture

Inside a cluster

Everything meets at the API server

A person with kubectl sends desired state to the API server in the control plane. The scheduler and the controllers watch the API server, which stores everything in etcd. Two worker nodes each hold a kubelet, told by a watch on the API server what to run, and it starts pods.
Only the API server talks to etcd. The others never call each other; they watch objects and write objects.

Who does what

PartJobIf it stops
API serverAuthenticates, authorizes, runs admission checks, validates and stores. Stateless, so run several behind a balancerNo changes. Running pods keep running
etcdHolds all cluster state, replicated with RaftWithout a majority nothing can be written
SchedulerChooses a node for each pod without oneNew pods stay Pending
Controller managerRuns the loops: Deployment, ReplicaSet, Node, EndpointSlice and moreNothing is repaired or replaced
Cloud controller managerCreates load balancers and checks machines with the providerCloud objects are not updated
kubeletOn each node: starts containers, runs probes, reports statusThat node stops reporting
kube-proxyOn most nodes: turns Service addresses into pod addressesRules go stale; some network plugins replace it

The core

The reconciliation loop

Each controller repeats three steps: observe, compare, act. A thermostat works this way. It does not remember that someone opened a window; it reads the temperature and heats. A loop that looks at the current state, rather than at each event, recovers after a crash by simply looking again.

Observe, compare, act

Running the loop twice must be harmless. That is why controllers compare counts and not orders.

From kubectl apply to a running pod

Solid arrows are requests, dashed arrows are watch events. The scheduler only fills in the node name.

Objects

Choosing a workload

What to run your program as

ObjectPromiseUse for
DeploymentN interchangeable pods, rolling updates, historyStateless services and APIs
StatefulSetStable names (db-0, db-1), a volume per pod, ordered start and stopDatabases, Kafka, ZooKeeper
DaemonSetOne pod on every chosen nodeLog collectors, monitoring agents
JobRuns until it succeedsBatch work, migrations
CronJobCreates Jobs on a scheduleNightly reports
Custom resourceYour own object type with your own controller (an operator)A database that knows how to back itself up

Most pods hold one container. A second one is a helper beside the main program, a sidecar: a proxy, a log shipper. Containers of one pod reach each other on localhost and are always placed together. For scheduled work in general see task schedulers.

Networking

Finding and reaching pods

Pods come and go, and their addresses change. A Service has a stable virtual address and a DNS name, and sends each connection to one of the ready pods that match its labels. CoreDNS is the usual name server.

A stable address in front of changing pods

Users send HTTPS to HTTP routing, a Gateway or Ingress, which calls http://api. The Service at 10.96.0.10 port 80 passes connections to a pod on node 1 and a pod on node 2, both on port 3000.
The Service is not a process. It is a set of rules on the nodes, so there is no single box to overload.

Service types

TypeReachable fromNote
ClusterIPInside the clusterThe default
NodePortEvery node, one portPort 30000 to 32767 by default
LoadBalancerOutside, through a cloud balancerOne balancer per Service
ExternalNameInsideA DNS alias for an outside name
HeadlessInsideclusterIP: None: DNS returns the pod addresses; StatefulSets use it
The full name is service.namespace.svc.cluster.local. Inside the same namespace service is enough.

Which way in?

Ingress and Gateway add host and path rules and TLS at one entry. Each needs an installed controller to do anything.

The Ingress API is frozen: it stays, but gets no new features, and the project recommends Gateway API. kube-proxy uses iptables by default, choosing a pod at random per connection; nftables is the planned default. A long-lived HTTP/2 or gRPC connection therefore stays on one pod, see load balancing in Kubernetes and service discovery.

Placement

Requests, limits and the scheduler

  1. 1

    Filter

    Drop nodes without enough unrequested CPU or memory, with a taint the pod does not tolerate, or outside its required affinity.

  2. 2

    Score

    Rank the rest: spread copies, prefer nodes that already hold the image, respect preferences.

  3. 3

    Bind

    Write the chosen node's name into the pod. The kubelet takes over.

How many pods fit on a node?

n=min⁡(⌊CPUfreeCPUreq⌋,⌊MEMfreeMEMreq⌋,110)min⁡(⌊3900500⌋,⌊140001024⌋,110)=min⁡(7,13,110)=7n = \min\left(\left\lfloor\frac{CPU_{free}}{CPU_{req}}\right\rfloor, \left\lfloor\frac{MEM_{free}}{MEM_{req}}\right\rfloor, 110\right) \qquad \min\left(\left\lfloor\tfrac{3900}{500}\right\rfloor, \left\lfloor\tfrac{14000}{1024}\right\rfloor, 110\right) = \min(7, 13, 110) = 7
Example node with 3,900 millicores and 14,000 MiB left after system use, and pods that request 500m and 1 GiB. CPU runs out first. 110 is the default number of pods per node.

The scheduler counts requests, not real use. Use above a CPU limit is throttled: the program slows. Use above a memory limit ends in an out-of-memory kill. Resources of a running container can now be changed in place, without recreating the pod.

Health

Three probes, three questions

ProbeQuestionWhen it fails
StartupHas it finished starting?The container is restarted once the allowance is used. The other two wait until it succeeds
ReadinessMay it receive traffic now?The pod leaves the Service's endpoints. It is not restarted
LivenessIs it stuck beyond repair?The container is restarted
A container that keeps crashing is restarted after 10 s, 20 s, 40 s and so on, at most 300 s. This wait is what CrashLoopBackOff means.

Releases

Rolling updates

How far a rollout may swing

most=R+⌈R⋅surge⌉fewest ready=R−⌊R⋅unavail⌋\text{most} = R + \lceil R \cdot surge\rceil \qquad \text{fewest ready} = R - \lfloor R \cdot unavail\rfloor
With the defaults of 25% each: 4 replicas swing between 3 and 5. 3 replicas swing between 3 and 4, because 0.75 rounds up for surge and down for unavailable.

A rollout of three replicas

An old pod goes only after a new one is ready. Without a readiness probe, ready just means started.

If new pods never become ready, the rollout stalls: old pods keep serving, and after 600 s the Deployment reports that progress stopped. Kubernetes does not roll back by itself. You, or a delivery tool, run kubectl rollout undo. Ten old revisions are kept by default. Choose the Recreate strategy only if two versions must never run together.

Scaling

More pods, bigger pods, more nodes

AutoscalerChangesPart of Kubernetes?
HPA (horizontal)Number of pods, from CPU, memory or custom metricsYes; needs Metrics Server, or an adapter for custom metrics
VPA (vertical)Requests of each pod, from observed useNo, install it
Cluster Autoscaler or KarpenterNumber and kind of nodesNo, install it or use the provider's
KEDAPods, from events such as queue depthNo, a separate project

The HPA formula

desired=⌈current×metrictarget⌉⌈3×9070⌉=⌈3.86⌉=4desired = \left\lceil current \times \frac{metric}{target} \right\rceil \qquad \left\lceil 3 \times \tfrac{90}{70}\right\rceil = \lceil 3.86 \rceil = 4
Checked every 15 s by default. A ratio within 10% of 1 changes nothing. Scaling down uses the highest recommendation of the last 5 minutes.

From load to a new machine

Seconds for a pod, often minutes for a machine (an assumption that depends on your provider and image size). Keep spare room for sudden peaks.

Failures

What happens when a node dies

A lost node

Traffic moves away early; replacement takes about five minutes unless you shorten the toleration.

Spread copies over nodes and zones with topology spread constraints, so that one loss takes a fraction. A PodDisruptionBudget limits voluntary disruption such as draining a node for an upgrade; it cannot prevent a power cut. A pod that is asked to stop gets 30 s by default to finish its work.

Operate

Limits, upgrades, security and cost

Numbers to know (v1.37)

WhatValue
Nodes per clusterUp to 5,000 in the project's supported design
Pods per clusterUp to 150,000
Containers per clusterUp to 300,000
Pods per node110
etcd data8 GiB suggested maximum; busy clusters move events to a second etcd
Version skewA kubelet may be up to three minor versions older than the API server, never newer
Vendors go further with changed control planes: Google says GKE supports 65,000 nodes. Beyond your limit, run several clusters.

Run it safely

AreaDo
AccessRBAC with few rights per service account; no shared admin
SecretsStored unencrypted in etcd by default: turn on encryption at rest, limit who can read them
NetworkA default-deny NetworkPolicy, then allow what is needed
QuotasResourceQuota and LimitRange per namespace
BackupsSnapshot etcd, store it elsewhere, rehearse the restore
UpgradesControl plane first, then nodes, one minor version at a time
Configuration sprawlTemplates (Helm) or overlays (Kustomize), reviewed in Git

The cost is people as much as machines: a control plane or a managed service fee, spare capacity on nodes, and a team that understands the platform. A namespace is not a hard security wall, because its pods share nodes and a kernel with others.

In practice

A small production setup

YAML
apiVersion: apps/v1kind: Deploymentmetadata:  name: apispec:  replicas: 3  selector:    matchLabels: { app: api }  template:    metadata:      labels: { app: api }    spec:      containers:        - name: api          image: registry.example.com/api:1.0          ports:            - containerPort: 3000          resources:            requests: { cpu: 100m, memory: 256Mi }            limits: { memory: 512Mi }          readinessProbe:            httpGet: { path: /ready, port: 3000 }            periodSeconds: 10          livenessProbe:            httpGet: { path: /live, port: 3000 }            periodSeconds: 20---apiVersion: v1kind: Servicemetadata:  name: apispec:  selector: { app: api }  ports:    - port: 80      targetPort: 3000
Different paths for the two probes. The Code tab has the autoscaler, Ingress, network policy and commands.

Decide

When to choose it, and when not

Choose Kubernetes

  • Many services (say ten or more) that ship and scale on their own
  • Load that swings, such as a yearly sale
  • Machine failures must need no person
  • Several teams share machines
  • Frequent releases with an easy way back
  • The same platform on more than one cloud or on site

Choose something simpler

  • One service on a few servers
  • A small team without platform skills
  • A monolith that scales up well
  • A tight budget for machines and people
  • Mainly databases: use a managed one
  • Speed to a first release: a platform service or functions

Alternatives

OptionSameDifferentChoose it when
Docker SwarmServices, scaling, rolling updates, declared stateBuilt into Docker, simpler, few extension points, smaller ecosystemSmall cluster, simplicity first
AWS ECS, with FargateContainers at scale, autoscaling, balancersAWS only, no control plane to run; Fargate removes the nodes tooAll on AWS, few operators
HashiCorp NomadScheduling, autoscaling, declared jobsOne binary; also runs plain programs, Java and VMs; works with Consul and VaultMixed workloads
Lambda, Cloud RunRuns and scales your codeNo cluster at all, billed by use, with more limitsEvent-driven or very uneven load

Summary

The whole topic in one minute.

Kubernetes stores the desired state in etcd behind one API server. Controllers create what is missing, the scheduler picks a node for each pod, and the kubelet on that node starts the containers. Services give stable addresses, probes decide who receives traffic, and autoscalers change the number of pods and nodes.

It suits many services that ship and scale separately, with people to run the platform. For one small service, a managed container platform is usually the better answer.

  • Desired state in etcd, control loops that close the gap.
  • Only the API server talks to etcd; the scheduler only picks a node; the kubelet starts containers.
  • Requests decide placement and HPA percentages; readiness decides traffic; liveness decides restarts.
  • A failed rollout stalls. Rolling back is your decision.
  • A dead node's pods are replaced after about five minutes by default.

Sources