Course contents

14. Cloud and Infrastructure Lesson 2 of 8

Containers

Watch images built from layers, containers isolated by namespaces and cgroups, an OOM kill that stays contained, and a rolling replace with zero errors.

14 minIntermediate6 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • An image is a stack of read-only layers; a container is processes started from it.
  • Order layers from least to most frequently changed so rebuilds and pulls move little data.
  • Namespaces give containers their own view; cgroups cap CPU, memory and I/O.
  • Containers start in milliseconds to seconds because no kernel boots.
  • Deploy by start → ready → drain → stop, never by stopping first; roll back by redeploying the old digest.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A container is a group of ordinary processes running on a host's kernel, fenced off so that they see their own file system, process list, network interfaces and hostname, and limited in how much CPU, memory and I/O they may use. It is started from a container image: a packaged, read-only file system with the app, its runtime and its libraries, plus metadata (entry command, environment, exposed ports). Images and runtimes follow the OCI (Open Container Initiative) specifications, so images built with one tool run with another (Docker, containerd, CRI-O, Podman).

Why it exists

"It works on my machine" usually means the machine differs: library versions, runtime versions, OS packages. An image freezes all of that, so the same bytes run on a laptop, in CI and in production. Because a container is just processes, it starts in milliseconds to seconds and costs little memory beyond the app itself, so one host can run dozens of them. That speed and density make frequent deploys, fast scaling and fast recovery practical.

How it works

Images and layers. An image is built from a recipe (a Dockerfile or equivalent). Each instruction that changes files produces a read-only layer; the layers are stacked with a union file system (overlayfs) and the container gets a thin writable layer on top. A layer is reused from the build cache only if it and everything below it are unchanged, so put rarely changing things (base OS, runtime, dependencies) at the bottom and the app code last. Registries store layers by content hash; a host pulls only the layers it lacks.

Digests and tags. Every image has a digest, a SHA-256 over its manifest, which identifies exactly one set of contents. Tags (web:2.0, latest) are movable names. Deploying by digest makes deploys reproducible and rollbacks exact.

Namespaces. Linux namespaces give a process group its own view of a kernel resource: PID (own process tree), network (own interfaces, routes, ports), mount (own file system tree), UTS (hostname), IPC, user (UID mapping, so root inside can be unprivileged outside) and cgroup.

cgroups. Control groups account for and limit resources: CPU (shares and quotas; a container over its CPU quota is throttled), memory (a container over its limit is OOM-killed by the kernel), block I/O and process counts.

Runtime. A high-level runtime (containerd, CRI-O) pulls images, prepares the file system and networking, and asks a low-level runtime (runc, crun) to create the namespaces and cgroups and start the process. A restart policy can start a container again when it exits.

Immutable deploys. You do not log in and change a running container. You build a new image, start containers from it, move traffic to them and stop the old ones. Configuration comes from the environment, mounted files or a secrets store, so the same image runs everywhere.

When to use it

  • Stateless services that you deploy often and scale horizontally.
  • Many small services on shared hosts, where a VM per service would waste memory.
  • Reproducible builds and environments across development, CI and production.
  • Batch jobs and workers that start, run and exit.

When not to

  • Untrusted or multi-tenant code on a shared kernel, unless you add a sandboxed runtime (gVisor, Kata Containers, microVMs).
  • Software that needs its own kernel, kernel modules or a different OS.
  • Large stateful systems where operating them in containers adds risk without benefit; a managed service or dedicated VMs may be simpler.

Trade-offs

Choice You gain You pay
Containers instead of VMs Fast starts, density, reproducible images Shared kernel, weaker isolation, limits to tune
Small base images (distroless, Alpine) Smaller pulls, fewer CVEs Harder debugging; musl vs glibc differences with Alpine
Tight memory limits Protects neighbours, predictable packing OOM kills when the limit is too low
CPU limits Caps noisy containers Throttling and latency spikes even when the host is idle
Rolling replace No extra fleet, no downtime Old and new versions run side by side for a while

Alternatives

  • VMs: stronger isolation and full OS control, slower boots and more overhead.
  • MicroVMs (Firecracker) and sandboxed runtimes: VM-grade isolation with container-like starts.
  • Serverless functions: no images or hosts to manage for short, event-driven work (many platforms now accept container images too).
  • Language-level packaging (a single static binary, a JAR): simpler, but the OS and runtime are still the host's.

Failure modes

  • OOM kills: a container exceeding its memory limit is killed, often repeatedly (a restart loop).
  • CPU throttling: a low CPU limit stretches latency even on an idle host.
  • Image drift: mutable tags such as latest make two environments run different code.
  • Deploy error bursts: stopping containers before traffic has moved away from them.
  • Huge images: slow pulls slow every deploy and scale-out; a bad layer order invalidates the cache on every build.
  • Kernel-level escape: a kernel or runtime vulnerability crosses the container boundary.
  • Lost data: anything written to the container's writable layer disappears with the container; use volumes or external storage.

In production

Build small images with a sensible layer order and scan them for vulnerabilities. Pin base images and deploy by digest. Run as a non-root user with minimal capabilities, a seccomp profile and a read-only root file system where possible. Set memory limits from measurements, be careful with CPU limits, and expose readiness and liveness endpoints. Deploy with start → ready → drain → stop, and keep previous images in the registry for rollbacks. On more than a handful of hosts, let an orchestrator place, restart and replace containers.

Common misconceptions

  • "A container is a small VM." It is processes on the host kernel; there is no guest kernel.
  • "Containers are secure by default." The boundary is real but thinner than a VM's; hardening and sandboxing matter for untrusted code.
  • "The image is the container." The image is the read-only template; containers are running instances with their own writable layer.
  • "Restarting a container fixes it." It restores a clean state from the image; if the bug or the limit is still there, it fails again.

Interview angle

Explain containers versus VMs in one sentence (shared kernel versus own kernel), then the consequences: start-up time, density, isolation. Know layers and caching well enough to fix a slow build, and why digests beat tags. For deployments, describe a zero-downtime rollout (new instance first, readiness gate, drain, stop) and how rollback works with immutable images. Mention resource limits and what happens when they are hit (throttling, OOM kills).

Model assumptions

This lesson uses a simplified model, not a benchmark. Each container is a simulated server with 2 workers and a 25 ms mean service time (lognormal, cv 0.35), about 80 req/s; traffic is Poisson. The image build, layer push and pull, and container start messages are a scripted illustration, with illustrative durations, not a simulated registry. OOM kills, restarts, starts and stops are timed actions on a compressed timeline. Draining is the balancer giving a container weight 0. Health checks run every 250 ms; 2 failures eject, 2 successes admit. Utilisation is the fraction of busy workers.

The lesson as textEvery step of the simulation, written out.
  1. 1. An image: the app and everything it needs, in layers

    A container image packages the app with its runtime and libraries. It is built from a recipe (a Dockerfile) as a stack of read-only layers: base OS files, the language runtime, the dependencies, the app code.

    This is how the three v1 containers got here: CI pushes the four layers to a registry (blue), the host’s container runtime pulls them (green), then starts three containers from the same image. They now serve 120 req/s, about 50% busy each.

    Scene: CI pushes four image layers to the registry; the host pulls the four layers and starts three v1 containers from the image. The three containers serve 120 requests per second at about half capacity; three v2 slots are empty.

    Key idea: An image is a stack of read-only layers; every container started from it gets exactly the same files.

  2. 2. v2: only the changed layer moves

    A developer changes the app code. CI rebuilds, but the base OS, runtime and dependency layers are unchanged, so they come from the build cache: CI pushes one small layer, and the host, which already has the lower three, pulls only that one.

    The new image gets a new digest (a SHA-256 of its contents). A tag such as web:2.0 can be moved; a digest cannot. Deploying by digest means every environment runs byte-for-byte the same thing. You never patch a running container: you build a new image and replace containers.

    Scene: CI pushes only the changed app layer for version 2, and the host pulls only that one layer. The v1 containers keep serving.

    Key idea: Order layers from least to most frequently changed, so rebuilds and pulls move only the top layer; images are immutable and addressed by digest.

  3. 3. Processes with walls: namespaces and cgroups

    A container is not a small VM. It is a group of ordinary processes on the host’s kernel. Namespaces give each group its own view (process IDs, network interfaces, mounts, hostname, users); cgroups cap what it may use (CPU, memory, I/O).

    At 0.8 s container 3 exceeds its memory limit and the kernel OOM-kills it. Only requests sent to container 3 fail; containers 1 and 2 never notice. Because starting a container is just starting a process (no kernel to boot), the runtime restarts it 0.3 s later and it is back in rotation within a few health checks. A VM reboot takes far longer.

    Scene: Container 3 is killed for exceeding its memory limit at 0.8 seconds and restarted 0.3 seconds later. Only requests routed to it fail; containers 1 and 2 are unaffected.

    Key idea: Containers are isolated processes sharing one kernel: cheap and fast to start, with limits enforced by cgroups.

  4. 4. Deploying the naive way: stop, then start

    Now deploy v2. The naive way: stop a v1 container and start a v2 one in its place, at 0.3 s.

    Two things go wrong. The requests container 1 was working on are cut off (errors). And the balancer keeps sending it new requests until two health checks have failed: those are refused. The v2 container meanwhile needs its own two good checks before it gets traffic. Repeat that for every container and every release, and users see a burst of errors each time.

    Scene: Container v1 · 1 is stopped at 0.3 seconds while still receiving traffic and v2 · 1 is started. Requests in flight on v1 · 1 fail, and new ones are refused until health checks remove it.

    Key idea: Stopping a container before traffic has moved away from it turns every deploy into an error burst.

  5. 5. Rolling replace: start, wait for ready, drain, stop

    Back to three v1 containers. This time each step goes: start a v2 container, wait until it passes two health checks, drain one v1 container (weight 0: no new requests, in-flight ones finish), then stop it. v2 · 1 starts at 0.2 s, v2 · 2 at 1.1 s, v2 · 3 at 2.0 s.

    There are never fewer than three containers in rotation and never more than four, so capacity never drops. The error rate stays at zero, and at the end only v2 serves traffic. Because the old image is still in the registry, rolling back is the same procedure with the old digest.

    Scene: Each v2 container is started and admitted after two health checks before one v1 container is drained and stopped. Three or four containers serve at all times, no request fails, and at the end only v2 receives traffic.

    Key idea: Replace, don’t mutate: bring the new container up first, move traffic, then stop the old one.

  6. 6. What containers change

    Containers package an app with its dependencies into an immutable, layered image, and run it as isolated processes on a shared kernel. Starts take milliseconds to seconds instead of a VM boot, and dozens of containers fit where a few VMs would.

    The price: a weaker boundary than a VM (one kernel for all, so a kernel exploit crosses it; sandboxed runtimes such as gVisor or Kata exist for untrusted code), limits you must set yourself, and many small moving parts to place and replace. Running them across many hosts is the job of an orchestrator such as Kubernetes, next.

    Scene: Three v2 containers serve all traffic on one host with a shared kernel; the v1 containers are stopped.

    Key idea: Containers trade some isolation for speed and density; immutability makes deploys and rollbacks repeatable.