Containers vs virtual machines
Junior Always asked 8 min
On this page
The question
What is the difference between a container and a virtual machine?
30-second answer
A VM (virtual machine) virtualizes hardware: a hypervisor runs several VMs, and each boots its own guest kernel and operating system, so it is strongly isolated but weighs gigabytes and starts in tens of seconds. A container virtualizes the operating system: it is an ordinary process on the host's kernel, isolated by namespaces and limited by cgroups, packaged with only its app and libraries. So it starts in about a second, weighs megabytes and packs densely, with a thinner wall, since all containers share one kernel.
Understand it
VM vs container stacks
CompareA hypervisor splits the hardware into three VMs (virtual machines). Each boots its own guest kernel and OS, so each weighs gigabytes and takes tens of seconds to start.
View as text
Three apps drawn as stacks of layers over the same hardware, with four facts above them: kernels, start time, size and what separates the apps.
Virtual machines: from the top, App for each app, Libs + JVM for each app, Guest kernel for each app, Hypervisor, shared, then the hardware. Kernels: 3, one per VM. Starts in: tens of seconds. Size: GBs per VM. Wall: the hypervisor. A hypervisor splits the hardware into three VMs (virtual machines). Each boots its own guest kernel and OS, so each weighs gigabytes and takes tens of seconds to start.
Containers: from the top, App for each app, Libs + JVM for each app, Container runtime, shared, Host OS: one Linux kernel, shared, then the hardware. Kernels: 1, shared by all. Starts in: about a second. Size: MBs per image. Wall: namespaces, cgroups. The same three apps as containers: plain processes on one host kernel, each packaged with only its libraries. No guest OS to boot, so they start in about a second.
Three apps drawn as stacks of layers over the same hardware, with four facts above them: kernels, start time, size and what separates the apps.
Virtual machines: from the top, App for each app, Libs + JVM for each app, Guest kernel for each app, Hypervisor, shared, then the hardware. Kernels: 3, one per VM. Starts in: tens of seconds. Size: GBs per VM. Wall: the hypervisor. A hypervisor splits the hardware into three VMs (virtual machines). Each boots its own guest kernel and OS, so each weighs gigabytes and takes tens of seconds to start.
Containers: from the top, App for each app, Libs + JVM for each app, Container runtime, shared, Host OS: one Linux kernel, shared, then the hardware. Kernels: 1, shared by all. Starts in: about a second. Size: MBs per image. Wall: namespaces, cgroups. The same three apps as containers: plain processes on one host kernel, each packaged with only its libraries. No guest OS to boot, so they start in about a second.
Takeaway: A VM virtualizes the hardware and carries a whole guest OS. A container virtualizes the OS: an isolated process on a shared kernel, so it is far lighter and faster, with a thinner wall.
What isolates a container
Tap the partsSelect a part to see what it does.
Tap a part. The left column limits what the process sees, the right column how much it uses, and every container runs on the shared kernel below.
View as text
At the top, one container: the process java -jar app.jar. Below it, two columns. The left one, namespaces, limits what the process can see: its process IDs, its network and its filesystem; the kernel also has UTS, IPC and user namespaces. The right one, cgroups, limits what it can use: memory, CPU and the number of processes. Under both, a wide bar for the host kernel that every container shares.
PID: The PID (process ID) namespace gives the container its own process tree: your app is PID 1 and cannot see host processes.
Network: The network namespace gives the container its own interfaces, IP address, routes and ports.
Mount: The mount namespace gives the container its own filesystem tree: the image layers plus a thin writable layer.
Memory: The memory cgroup caps RAM.
CPU: The CPU cgroup grants a quota of CPU time per period, such as 1.5 CPUs.
PIDs limit: The pids cgroup caps how many processes and threads the container may create.
Host kernel: Every container on the host shares this one kernel.
At the top, one container: the process java -jar app.jar. Below it, two columns. The left one, namespaces, limits what the process can see: its process IDs, its network and its filesystem; the kernel also has UTS, IPC and user namespaces. The right one, cgroups, limits what it can use: memory, CPU and the number of processes. Under both, a wide bar for the host kernel that every container shares.
PID: The PID (process ID) namespace gives the container its own process tree: your app is PID 1 and cannot see host processes.
Network: The network namespace gives the container its own interfaces, IP address, routes and ports.
Mount: The mount namespace gives the container its own filesystem tree: the image layers plus a thin writable layer.
Memory: The memory cgroup caps RAM.
CPU: The CPU cgroup grants a quota of CPU time per period, such as 1.5 CPUs.
PIDs limit: The pids cgroup caps how many processes and threads the container may create.
Host kernel: Every container on the host shares this one kernel.
Takeaway: A container is a normal process. Namespaces limit what it can see: its processes, network and files. cgroups limit what it can use: memory, CPU and process count. The kernel underneath is shared.
In code
docker run --rm alpine:3.20 ps
# PID USER TIME COMMAND
# 1 root 0:00 ps <- its own PID namespace: no host process in sight
docker run --rm alpine:3.20 sh -c 'hostname; hostname -i'
# 1fd68de7611a <- UTS namespace: the hostname is the container ID
# 172.17.0.2 <- network namespace: its own interface and IP
ps -ef | grep 'sleep 300' # on a Linux host, a running container is a normal processdocker run --rm --memory=256m --cpus=1.5 --pids-limit=100 alpine:3.20 sh -c '
cat /sys/fs/cgroup/memory.max # 268435456, which is 256 MiB
cat /sys/fs/cgroup/cpu.max # 150000 100000: 150 ms of CPU every 100 ms
cat /sys/fs/cgroup/pids.max' # 100
docker stats --no-stream # live usage against each container's limit// docker run --rm --memory=1g --cpus=2 my-app
public class Limits {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
System.out.println("CPUs: " + rt.availableProcessors()); // 2, from cpu.max
System.out.println("Max heap MB: " + rt.maxMemory() / (1024 * 1024)); // about 250: a quarter of 1 GiB
System.out.println("PID: " + ProcessHandle.current().pid()); // 1 when java is the entrypoint
}
}# Root with every capability and the host's devices: one breakout and the host is yours
Wrong docker run --privileged my-app
# A non-root user, a read-only filesystem and no extra capabilities
Right docker run --user 1000:1000 --read-only --tmpfs /tmp \
Right --cap-drop ALL --security-opt no-new-privileges my-appSolve it
docker stop hangs, then the container exits with code 137
A Spring Boot service starts from an entrypoint script, start.sh, that sets a few variables and then runs
java -jar app.jar. Every docker stop waits several seconds, the container exits with code 137, and requests in
flight during a deploy fail instead of finishing. Explain why and fix it.
- Read the exit code. 137 is 128 plus 9, SIGKILL.
docker stopsends SIGTERM, waits a grace period, 10 seconds by default, then sends SIGKILL. A JVM that received SIGTERM would exit with 143, 128 plus 15. - Find PID 1.
docker exec <container> psshows the script’s shell as PID 1 and java as its child. The shell does not forward SIGTERM, and PID 1 ignores signals it has no handler for, so the JVM never hears it. - Make java PID 1. End the script with
exec java -jar app.jar, so java replaces the shell, or drop the script and use the exec form ofENTRYPOINT, which starts java without a shell. - Let Spring drain. With SIGTERM delivered, Spring Boot’s graceful shutdown stops taking new requests and lets
active ones finish, within
spring.lifecycle.timeout-per-shutdown-phase, 30 seconds by default. - Check.
psnow shows java as PID 1,docker stopreturns in well under a second when idle, the exit code is 143, and the logs show the graceful shutdown.
FROM eclipse-temurin:21-jre
COPY app.jar /app/app.jar
COPY --chmod=755 start.sh /app/start.sh
ENTRYPOINT ["/app/start.sh"]
# start.sh
# #!/bin/sh
# export JAVA_OPTS="-XX:MaxRAMPercentage=75"
# exec java $JAVA_OPTS -jar /app/app.jar # exec: java becomes PID 1How to answer
- VMs are isolated by the hypervisor, each with its own kernel; containers share the host kernel.
- Namespaces decide what a container sees; cgroups decide how much CPU, memory and processes it gets.
- Containers are lighter and faster, so you run more per machine and redeploy in seconds.
- In the cloud, containers usually run inside VMs, combining both.
Common mistakes
- Calling a container a lightweight VM with its own kernel.
- Claiming containers are as isolated as VMs, or that a Linux container runs natively on a Windows kernel.
Follow-up questions
What actually isolates a container from the host and from other containers?
Two Linux kernel features. Namespaces give the process its own view: the PID (process ID) namespace its own process tree, the network namespace its own interfaces and ports, the mount namespace its own filesystem, plus UTS for the hostname, IPC and user namespaces. cgroups, control groups, limit and account resources: memory, CPU time, process count and disk I/O. A container runtime sets both up and starts the process inside them; there is no other magic.
- Namespaces limit what a process can see.
- cgroups limit what a process can use, and report usage for docker stats.
- Capabilities, seccomp and read-only filesystems narrow what a root process may do.
Is a container as secure as a VM? How would you harden one?
No. Every container makes system calls to the same kernel, so a kernel bug or a misconfiguration can let one escape to the host and its neighbors; a VM's guest kernel and hypervisor are a much smaller shared surface. Harden a container by running it as a non-root user, dropping capabilities, using a read-only root filesystem and the default seccomp profile, never using --privileged or mounting the Docker socket, and keeping images small and patched.
- Root in a container is root on the kernel, minus what capabilities remove.
- Rootless Docker and user namespaces map container root to an unprivileged host user.
- For untrusted code, add a stronger sandbox, such as gVisor or Kata Containers.
Docker, containerd, runc, OCI. Who actually runs a container?
A layered stack. The docker CLI (command-line interface) talks to dockerd, the Docker daemon, which hands containers to containerd, a container runtime that pulls images and supervises containers. containerd starts runc, the low-level runtime that creates the namespaces and cgroups and starts the process. The OCI (Open Container Initiative) standardizes the image format and the runtime, so an image built by Docker runs on containerd, CRI-O or Podman alike.
- Kubernetes talks to containerd or CRI-O through the CRI (Container Runtime Interface).
- Kubernetes 1.24 removed dockershim, so Docker Engine is no longer a Kubernetes runtime, but Docker-built images still run.
- Podman runs the same images without a daemon.
Can you run a Windows container on a Linux host, or a Linux container on Windows?
Not directly, because a container uses the host's kernel and makes its system calls. A Linux container needs a Linux kernel, and a Windows container a Windows kernel. Docker Desktop on Windows and macOS runs Linux containers inside a small Linux VM. The CPU architecture must match too: an arm64 image does not run on an amd64 host without emulation, which is why images are published for several platforms.
- Image, kernel and CPU architecture must agree.
- Multi-platform images hold one variant per architecture, and the runtime picks the right one.
- docker buildx build --platform linux/amd64,linux/arm64 builds both.
When would you still choose a VM over a container?
When the workload needs what a shared kernel cannot give: another operating system or kernel version, custom kernel modules, or strong isolation between tenants who do not trust each other, such as running customer code. Also for legacy software that expects a whole machine, with init systems, many processes and local state. For packaging and running your own stateless services, containers win on density, speed and portability.
- Different OS or kernel means a VM.
- Hostile multi-tenancy means a VM boundary, or a micro-VM per container.
- In practice it is both, containers inside VMs.
Your Mac runs Linux containers. Whose kernel do they use?
A Linux VM's. A container needs a kernel of its own kind, and macOS has none for Linux, so Docker Desktop starts a small Linux VM and runs every container inside it. On Windows it uses WSL 2, which is also a lightweight Linux VM. The containers share that VM's kernel.
Why do cloud providers run containers inside VMs instead of on bare metal?
Because tenants must not share a kernel. The VM boundary separates customers, and containers pack one customer's apps densely inside it. Services like AWS (Amazon Web Services) Fargate even give each task its own micro-VM, such as Firecracker, to get VM isolation at container speed.
Check yourself
Show answers
- One, the host's: Correct. Containers are processes on the host kernel; none boots its own.
- Twenty, one per container: Incorrect. That describes 20 VMs, each with a guest kernel.
- Twenty-one, the host's plus one per container: Incorrect. Containers carry libraries, not a kernel.
Show answers
- A PID namespace hides the processes; the memory cgroup caps the memory: Correct. Namespaces limit what a process sees; cgroups limit what it uses.
- A cgroup hides the processes; a namespace caps the memory: Incorrect. The two are swapped.
- The hypervisor enforces both: Incorrect. Containers do not use a hypervisor; the host kernel enforces both.
Show answers
- It is throttled and runs slower: Correct. CPU time past the quota waits for the next period; nothing is killed.
- It is killed with exit code 137: Incorrect. That is what happens past a memory limit, not a CPU limit.
- It takes the extra CPUs from idle containers: Incorrect. A quota is a hard cap, whatever is idle.