Virtualization & Containers
Most code today doesn't run directly on a physical machine: it runs in a virtual machine in the cloud, in a container on a laptop, or in both at once. Both technologies let many isolated workloads share one computer, but they isolate at different levels. A VM virtualizes the hardware and runs its own kernel; a container virtualizes the operating system's view and shares the host's kernel. This lesson explains the machinery behind each, on Linux and on Windows.
Virtual machines
A hypervisor creates virtual machines, each with virtual CPUs, memory, disks and network cards, and runs a complete guest OS in each.
Type 1 (bare metal) Type 2 (hosted)
+-------+ +-------+ +-------+ +-------+ +-------+
| VM 1 | | VM 2 | | VM 3 | | VM 1 | | VM 2 |
| guest | | guest | | guest | | guest | | guest |
| kernel| | kernel| | kernel| | kernel| | kernel|
+-------+ +-------+ +-------+ +-------+ +-------+
+---------------------------+ +-----------------+ +------+
| hypervisor | | VirtualBox/VMware| | apps |
+---------------------------+ +-----------------+-+------+
| hardware | | host OS (Windows/macOS) |
+---------------------------+ +---------------------------+
| hardware |
Hyper-V, KVM, Xen, ESXi +---------------------------+KVM blurs the line: it is a Linux kernel module that turns Linux itself into a type 1 hypervisor; each VM is a normal Linux process (usually QEMU) whose virtual CPUs are threads. Hyper-V is covered in WSL & Hyper-V.
How a guest kernel can run safely
A guest kernel expects to run in kernel mode and to control page tables and devices. Three techniques make that possible:
| Technique | Idea |
|---|---|
| Hardware-assisted virtualization (Intel VT-x, AMD-V, ARM EL2) | the CPU gets a new "guest mode". The guest runs at full speed; sensitive instructions (I/O, some control registers) cause a VM exit into the hypervisor, which emulates them and resumes the guest |
| Second-level address translation (Intel EPT, AMD NPT) | the CPU translates guest-virtual → guest-physical → host-physical addresses in hardware, so the hypervisor doesn't have to shadow every page table |
| Paravirtualization | the guest knows it is virtual and uses efficient interfaces instead of emulated hardware: virtio devices on KVM, VMBus synthetic devices on Hyper-V |
VM exits are the main cost of virtualization, so hypervisors try hard to avoid them. Emulating an old network card can need several exits per packet; a virtio device batches many packets per notification.
PACKETS = 10_000
EXIT_US = 1.5 # cost of one VM exit + re-entry
designs = {
"emulated e1000 NIC": PACKETS * 4, # several register accesses per packet
"virtio-net": PACKETS // 32 + 1, # one notification per batch of 32
"SR-IOV passthrough": 0, # guest drives a hardware function directly
}
for name, exits in designs.items():
print(f"{name:<20} {exits:>6} VM exits {exits * EXIT_US / 1000:6.2f} ms overhead")emulated e1000 NIC 40000 VM exits 60.00 ms overhead
virtio-net 313 VM exits 0.47 ms overhead
SR-IOV passthrough 0 VM exits 0.00 ms overhead
SR-IOV lets one physical network card present many "virtual functions" that are handed straight to VMs; the IOMMU keeps their DMA confined to the right guest.
Containers on Linux
A container is just a group of ordinary processes that the kernel shows a private view of the system. Three kernel features build it:
| Feature | What it isolates or limits |
|---|---|
| Namespaces | what a process can see: pid (own PID 1), mnt (own mount table / root file system), net (own interfaces, ports, routes), uts (own hostname), ipc, user (root inside ≠ root outside), cgroup, time |
| cgroups v2 | how much it can use: CPU weight and quota (cpu.max), memory limit (memory.max), PIDs, I/O bandwidth |
| Union / overlay file systems | image layers stacked read-only with one writable layer on top (OverlayFS) |
Security is tightened further with seccomp filters (blocking dangerous system calls), dropped capabilities and SELinux/AppArmor profiles. Container engines (Docker, Podman, containerd) and Kubernetes only configure these kernel features.
This course's Linux sandbox is itself a container. Every process has a link per namespace in /proc/self/ns, and the hostname comes from its own UTS namespace:
ls /proc/self/ns
hostnamecgroup
ipc
mnt
net
pid
pid_for_children
time
time_for_children
user
uts
tad
The hostname tad was set for this container's UTS namespace; the host machine has a different one. The PID namespace works the same way: ps -e inside a container lists only the container's own processes, starting from its own PID 1, while on a normal Linux desktop it lists hundreds.
Containers on Windows
Windows has its own container support, built on job objects (resource limits, the cgroups counterpart), server silos (namespace isolation for the object manager, registry and network) and a layered file system filter. Windows containers come in two modes:
- Process isolation: containers share the host kernel, like Linux containers. The container image's Windows version must match the host's.
- Hyper-V isolation: each container runs in its own tiny utility VM with its own kernel. Stronger isolation, slightly slower start.
Linux containers on a Windows (or macOS) desktop always run inside a Linux VM: Docker Desktop uses the WSL 2 VM on Windows and a lightweight VM on macOS.
Comparing the costs
The trade-off is isolation versus overhead. A VM reserves memory for a whole guest kernel and boots it; a container starts as fast as a process and shares the host's kernel and page cache:
| Virtual machine | Container | |
|---|---|---|
| Isolation boundary | hardware (hypervisor) | kernel (namespaces, cgroups) |
| Own kernel | yes, any OS | no, shares the host kernel |
| Start time | seconds (micro-VMs like Firecracker: ~125 ms) | milliseconds |
| Memory overhead | guest kernel + OS services (hundreds of MB) | almost none |
| Typical density | tens per host | hundreds per host |
| Kernel bug in a workload | contained in the VM | can affect the host |
| Run Windows on Linux (or vice versa) | yes | no |
This model packs workloads onto a 64 GB host both ways. VMs reserve their full memory plus a guest-OS overhead; containers only reserve their cgroup request and share one kernel:
HOST_GB = 64
HOST_OS_GB = 4 # host kernel + services
VM_GUEST_OS_GB = 1.5 # each VM's own kernel and OS services
apps = [("web", 2.0), ("api", 3.0), ("worker", 1.5), ("cache", 4.0)] # (name, memory needed)
def pack(per_app_overhead):
free = HOST_GB - HOST_OS_GB
placed = []
while True:
for name, mem in apps:
need = mem + per_app_overhead
if need > free:
return placed, free
free -= need
placed.append(name)
for label, overhead in [("VMs", VM_GUEST_OS_GB), ("containers", 0.0)]:
placed, free = pack(overhead)
counts = {name: placed.count(name) for name, _ in apps}
print(f"{label:<10} {len(placed):>2} workloads {counts} free {free:.1f} GB")VMs 14 workloads {'web': 4, 'api': 4, 'worker': 3, 'cache': 3} free 2.5 GB
containers 23 workloads {'web': 6, 'api': 6, 'worker': 6, 'cache': 5} free 1.0 GB
Limits and the OOM killer
A cgroup memory limit is enforced by the kernel. When the processes in a container need more than memory.max and the kernel can't reclaim enough page cache, the OOM killer kills a process inside that cgroup (Docker then reports OOMKilled: true and exit code 137 = 128 + SIGKILL). The rest of the host is unaffected. CPU limits work differently: going over cpu.max doesn't kill anything, the cgroup is just throttled until the next period.
def run_container(name, limit_mb, cpu_quota, usage):
print(f"{name}: memory.max={limit_mb}M cpu.max={cpu_quota}")
for step, (mem, cpu) in enumerate(usage, 1):
notes = []
if cpu > cpu_quota:
notes.append(f"throttled ({cpu:.1f} wanted, {cpu_quota:.1f} allowed)")
if mem > limit_mb:
print(f" step {step}: {mem}M > {limit_mb}M -> OOM kill, exit code {128 + 9}")
return
print(f" step {step}: {mem:>4}M cpu {min(cpu, cpu_quota):.1f} {' '.join(notes)}".rstrip())
print(" finished normally")
run_container("api", 512, 1.0, [(200, 0.4), (350, 1.6), (480, 0.9)])
run_container("leaky", 256, 0.5, [(120, 0.2), (240, 0.3), (300, 0.3)])api: memory.max=512M cpu.max=1.0
step 1: 200M cpu 0.4
step 2: 350M cpu 1.0 throttled (1.6 wanted, 1.0 allowed)
step 3: 480M cpu 0.9
finished normally
leaky: memory.max=256M cpu.max=0.5
step 1: 120M cpu 0.2
step 2: 240M cpu 0.3
step 3: 300M > 256M -> OOM kill, exit code 137
Real limits are set like this (sample output — yours will differ):
ada@ubuntu:~$ docker run -d --name api --memory 512m --cpus 1 nginx:1.27
ada@ubuntu:~$ cat /sys/fs/cgroup/system.slice/docker-$(docker inspect -f '{{.Id}}' api).scope/memory.max
536870912Learn more: WSL & Hyper-V · /proc & /sys · Virtual Memory & Paging
Test yourself
What is the main difference between a container and a VM?
- Containers are always slower
- A container shares the host kernel; a VM runs its own guest kernel on virtual hardware
- VMs can't run Linux
- Containers need a hypervisor
Which Linux kernel feature limits how much memory a container may use?
- namespaces
- cgroups
- seccomp
- OverlayFS
Why does virtio-net perform better than an emulated network card?
- It uses a faster cable
- The guest knows it is virtual and batches work, causing far fewer VM exits
- It skips TCP
- It runs in user mode