A container packages an application with everything it needs to run (runtime, libraries, config) into an image that behaves the same on a laptop, in CI and in production. An orchestrator such as Kubernetes runs thousands of those containers across a fleet of machines: it places them, restarts them when they crash, connects them through stable network names, scales them with load and rolls out new versions without downtime. Together they are the default way modern services, and especially microservices, are deployed.
Think of it like
Shipping containers and the port authority
Before standard shipping containers, every cargo was loaded by hand in its own way. The steel box changed that: cranes, ships and trucks handle any container the same way, whatever is inside. Docker did the same for software. Kubernetes is the port authority: you file a manifest saying "I need three of these boxes on ships at all times", and it decides which ship has room, notices when one sinks, and puts replacement boxes on another ship without being asked.
Containers vs virtual machines
A virtual machine emulates hardware and boots a complete guest operating system on a hypervisor. A container is just a normal Linux process that the kernel isolates: it sees its own filesystem, process tree and network stack, but shares the host's kernel with every other container. That one difference drives everything else.
| Virtual machine | Container | |
|---|---|---|
| Isolation boundary | Hypervisor; each VM has its own kernel | Kernel namespaces and cgroups; one shared kernel |
| Startup time | Tens of seconds to minutes (boot an OS) | Milliseconds to seconds (start a process) |
| Image size | Gigabytes | Megabytes to a few hundred megabytes |
| Density per host | Tens | Hundreds |
| Security isolation | Strong | Weaker: a kernel exploit can escape; hardened with seccomp, AppArmor/SELinux, rootless mode or sandboxed runtimes |
| Typical use | Multi-tenant isolation, different OSes | Packaging and running services |
The kernel features underneath
- Namespaces
- Give a process its own view of a global resource: PID (its own process tree, where it is PID 1), network (its own interfaces and ports), mount (its own filesystem tree), UTS (hostname), IPC, user (UID mapping, so root inside can be unprivileged outside) and cgroup.
- cgroups
- Control groups limit and account for resources: CPU shares and quotas, memory (exceed it and the kernel's OOM killer ends the process), process count and I/O. This is how one noisy container cannot starve its neighbors.
- Image
- A read-only, layered filesystem snapshot plus metadata (entrypoint, environment, ports), described by the OCI image specification so any compliant runtime can run it.
- Layer
- Each build step adds a layer containing only the files it changed. Layers are content-addressed by hash, shared between images and cached, so pulling a new version downloads only the changed layers.
- Union filesystem
- OverlayFS stacks the read-only image layers and adds a thin writable layer per container. Writes are lost when the container is removed, so persistent data belongs in volumes.
- Registry
- A server that stores and distributes images by name, tag and digest (Docker Hub, GHCR, ECR, Artifact Registry).
Building images well
A Dockerfile lists the steps to build an image. Each instruction becomes a cached layer, so ordering matters: put things that rarely change (base image, dependency installs) first and your frequently changing source code last. A multi-stage build compiles in a fat image with the full toolchain and copies only the result into a tiny runtime image.
# ---- Stage 1: build with the full Go toolchain (hundreds of MB) ----
FROM golang:1.27 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download # cached until dependencies change
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server
# ---- Stage 2: ship only the static binary (a few MB of base image) ----
FROM gcr.io/distroless/static-debian13:nonroot
COPY --from=build /out/server /server
# never run as root (Dockerfile comments must start a line)
USER nonroot:nonroot
EXPOSE 8080
ENTRYPOINT ["/server"]- Small, minimal bases (distroless, Alpine, or
scratchfor static binaries) mean faster pulls and fewer packages with CVEs. No shell also means less for an attacker to use. - Pin versions and deploy by immutable tag or digest.
:latestmakes it impossible to know what is running or to roll back reliably. - One process per container, logging to stdout and stderr, configured by environment variables (the twelve-factor style).
- No secrets in images: anything in a layer can be extracted by whoever pulls the image, even if a later step deletes it.
- Scan and sign images in CI (Trivy, Grype; Sigstore cosign) and only admit signed images to production.
Kubernetes: desired state, continuously reconciled
Kubernetes grew out of Google's experience running Borg and was open-sourced in 2014. Its central idea is declarative configuration: you don't tell it to start three containers, you declare that three replicas should exist. Controllers then compare that desired state with what is actually running and act to close the gap, forever. Every feature below is built on that loop.
| Object | What it is | Typical use |
|---|---|---|
| Pod | One or more containers that share a network namespace (one IP) and volumes, scheduled together | The unit of deployment; usually one app container, sometimes plus sidecars |
| ReplicaSet | Keeps N identical pods running | Managed for you by a Deployment |
| Deployment | Manages ReplicaSets to roll out new versions and roll back | Stateless services |
| Service | A stable virtual IP and DNS name load-balancing across pods selected by labels | Service-to-service discovery: http://payments |
| Ingress / Gateway API | HTTP routing from outside the cluster to Services by host and path, with TLS | Public entry point |
| ConfigMap | Non-secret configuration as key-value pairs or files | Feature settings, config files |
| Secret | Sensitive values, mounted as files or env vars | Passwords, API keys (base64-encoded, not encrypted by default) |
| StatefulSet | Pods with stable names (db-0, db-1), stable per-pod storage and ordered rollout | Databases, Kafka, ZooKeeper |
| DaemonSet | Exactly one pod on every (or every matching) node | Log shippers, metrics agents, network plugins |
| Job / CronJob | Pods that run to completion, once or on a schedule | Migrations, batch jobs, nightly reports |
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 3
selector:
matchLabels: { app: web }
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1 # at most 4 pods exist during a rollout
maxUnavailable: 0 # never fewer than 3 ready pods
template:
metadata:
labels: { app: web }
spec:
containers:
- name: web
image: registry.example.com/web:1.8.2 # immutable tag, never :latest
ports:
- containerPort: 8080
envFrom:
- configMapRef: { name: web-config }
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef: { name: web-db, key: password }
resources:
requests: { cpu: 250m, memory: 256Mi } # what the scheduler reserves
limits: { memory: 512Mi } # exceed it and the container is OOMKilled
startupProbe:
httpGet: { path: /healthz, port: 8080 }
periodSeconds: 2
failureThreshold: 30 # up to 60 s to boot
livenessProbe:
httpGet: { path: /healthz, port: 8080 }
periodSeconds: 10
readinessProbe:
httpGet: { path: /ready, port: 8080 }
periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
name: web
spec:
selector: { app: web } # routes to every ready pod with this label
ports:
- port: 80
targetPort: 8080The control plane
A cluster is split into a control plane, which stores and acts on desired state, and worker nodes, which run pods. Components never call each other directly: they all read and write objects through the API server and watch for changes, which keeps them loosely coupled and individually restartable.
- 1
Observe
A controller watches the objects it owns through the API server and gets notified of every change.
- 2
Diff
It compares desired state (the object's
spec) with observed state (status, child objects, the real world). - 3
Act
It takes the smallest step toward desired state: create a pod, delete one, update a load balancer.
- 4
Repeat
It loops forever. Because it is level-triggered ("is the world right?") rather than edge-triggered ("what event just happened?"), a missed event or a crash in the middle of an action is harmless: the next pass fixes it.
Health probes
| Probe | Question it answers | On failure | Keep it |
|---|---|---|---|
| Startup | Has the app finished booting? | Keeps checking until the threshold, then restarts; liveness and readiness wait until it passes | Generous for slow starters (JVM warm-up, cache loading) |
| Liveness | Is the process stuck beyond recovery? | Container is restarted | Shallow: no checks of databases or other services |
| Readiness | Should this pod receive traffic right now? | Pod is removed from Service endpoints; not restarted | Honest: fail while warming up, overloaded or draining on shutdown |
Requests, limits and graceful shutdown
- Requests are what the scheduler reserves on a node; set them from observed usage or pods will be packed onto nodes that cannot actually serve them.
- Memory limits are enforced by the kernel: exceed one and the container is OOMKilled (exit code 137). CPU limits throttle instead, which can add latency even when the node has idle CPU, so many teams set CPU requests but no CPU limit.
- QoS classes follow from these:
Guaranteed(requests equal limits),BurstableandBestEffort. Under node memory pressure, BestEffort pods are evicted first. - Graceful shutdown: on termination a pod receives
SIGTERM, is removed from endpoints, and getsterminationGracePeriodSeconds(30 s by default) to finish in-flight requests beforeSIGKILL. Handle the signal, stop accepting work and drain.
Autoscaling
| Autoscaler | Scales | Based on | Notes |
|---|---|---|---|
| Horizontal Pod Autoscaler (HPA) | Number of pod replicas | CPU, memory, or custom and external metrics (requests per second, queue depth) | Built in; the workhorse for stateless services |
| Vertical Pod Autoscaler (VPA) | CPU and memory requests per pod | Historical usage | Add-on; good for right-sizing. Don't let it and HPA both act on the same CPU or memory metric |
| Cluster Autoscaler / Karpenter | Number of nodes | Pending pods that fit nowhere; underused nodes | Adds capacity in minutes, not seconds |
| KEDA | Replicas, including to and from zero | Event sources: Kafka lag, queue length, cron | Event-driven workers |
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 3
maxReplicas: 30
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 60 # percent of the pods' CPU requests
behavior:
scaleDown:
stabilizationWindowSeconds: 300Deployment strategies
| Strategy | How it works | Rollback | Cost and risk |
|---|---|---|---|
| Recreate | Stop all old pods, then start new ones | Redeploy the old version | Downtime; only for dev or apps that cannot run two versions |
| Rolling update | Replace pods a few at a time (maxSurge, maxUnavailable), gated by readiness | kubectl rollout undo; takes another rollout | Kubernetes default; both versions serve traffic during the rollout |
| Blue-green | Deploy the full new version (green) next to the old (blue), test it, then switch the router | Switch back: seconds | Double capacity during the switch; every user moves at once |
| Canary | Send a small slice of traffic (1 to 5%) to the new version, compare metrics, increase step by step | Set the canary's weight to 0 | Needs good metrics and traffic splitting; the safest for big fleets |
| Feature flags | Ship code dark, then enable it at runtime for a percentage, segment or cohort | Flip the flag off, no deploy | Separates deploy from release; flags need cleanup |
kubectl set image deployment/web web=registry.example.com/web:1.9.0
kubectl rollout status deployment/web # blocks; fails if the rollout stalls
kubectl rollout history deployment/web # each revision is a kept ReplicaSet
kubectl rollout undo deployment/web # back to the previous revision
kubectl rollout undo deployment/web --to-revision=7Implementation
The heart of every Kubernetes controller: repeatedly compare desired and actual state and take one step toward the desired state. It is idempotent and level-triggered, so errors are simply retried on the next pass.
import itertools
from dataclasses import dataclass, field
@dataclass
class FakeCluster:
desired: dict[str, int] = field(default_factory=dict)
pods: dict[str, list[str]] = field(default_factory=dict)
_ids: itertools.count = field(default_factory=itertools.count)
def start_pod(self, app: str) -> None:
self.pods.setdefault(app, []).append(f"{app}-{next(self._ids)}")
def stop_pod(self, app: str, name: str) -> None:
self.pods[app].remove(name)
def reconcile(cluster: FakeCluster, app: str) -> None:
"""One pass: diff desired vs actual and take the smallest step to fix it."""
want = cluster.desired.get(app, 0)
have = list(cluster.pods.get(app, []))
if len(have) < want:
for _ in range(want - len(have)):
cluster.start_pod(app)
elif len(have) > want:
for name in have[: len(have) - want]:
cluster.stop_pod(app, name)
if __name__ == "__main__":
c = FakeCluster(desired={"web": 3})
reconcile(c, "web")
print(c.pods["web"]) # ['web-0', 'web-1', 'web-2']
c.pods["web"].pop() # a pod crashes
reconcile(c, "web")
print(c.pods["web"]) # ['web-0', 'web-1', 'web-3']
c.desired["web"] = 1 # someone scales down
reconcile(c, "web")
print(c.pods["web"]) # ['web-3']
reconcile(c, "web") # idempotent: nothing changesKey takeaways
- Containers are isolated processes (namespaces for what they see, cgroups for what they use) sharing the host kernel, which makes them far lighter than VMs but less isolated.
- Build small, layered, pinned images with multi-stage Dockerfiles; never bake in secrets or deploy
:latest. - Kubernetes is a set of controllers reconciling declared desired state, stored in etcd, through the API server. Self-healing, scaling and rollouts are all that one loop.
- Liveness restarts, readiness removes from traffic, startup protects slow boots; keep liveness shallow.
- HPA scales pods, VPA sizes them, the cluster autoscaler adds nodes, and all of them react with lag.
- Rolling, blue-green, canary and feature flags trade cost for blast radius; every one depends on backward-compatible database changes for rollback.
Common pitfalls
- Liveness probes that check downstream dependencies, causing fleet-wide restart storms during a brief outage.
- Missing or made-up resource requests, leading to overpacked nodes, OOMKills and noisy neighbors.
- Deploying mutable tags like
:latest, so you cannot tell what is running or roll back to a known image. - Treating Kubernetes Secrets as encrypted without enabling encryption at rest and restricting RBAC access to them.
- Running stateful databases on Kubernetes without understanding StatefulSets, persistent volumes and the operator's failover behavior.
Interview tips
- Explain the difference between a container and a VM in terms of the shared kernel, namespaces and cgroups.
- Describe what happens after
kubectl apply: API server, etcd, controllers, scheduler, kubelet. It demonstrates you understand reconciliation. - When asked how to deploy safely, compare rolling, blue-green and canary, and mention automated rollback on metrics plus expand-and-contract migrations.
Real-world applications
- Managed Kubernetes services (GKE, EKS, AKS) running most large companies' microservice fleets.
- Serverless container platforms such as Cloud Run and AWS Fargate, which run your images without exposing nodes.
- Progressive delivery tools (Argo Rollouts, Flagger) and feature-flag platforms automating canaries and gradual releases.
- Kubernetes operators managing stateful systems such as PostgreSQL, Kafka and Elasticsearch clusters.
Test yourself
What fundamentally distinguishes a container from a virtual machine?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.