Virtual machines vs containers
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite must run the same way on your laptop, a test server and the real server. Giving every copy of the app its own whole computer is slow and heavy. Is there something lighter?
Virtual machines and containers side by side
A virtual machine (VM) is a software copy of a whole computer. A hypervisor splits the real hardware into several VMs, and each VM boots its own guest operating system with its own kernel.
A VM carries a whole guest operating system. A container skips it and shares the one kernel the host already runs. The picture compares the two stacks on the same hardware.
The hypervisor (for example Hyper-V, VirtualBox or VMware) is the program that splits the hardware. The kernel is the core of an operating system: it starts processes, hands out memory and talks to the hardware.
All containers on a machine share the host kernel, the one kernel the real machine already runs. Each container brings only the files its app needs: for ShopLite, a JDK and the jar.
What a container really is: namespaces and cgroups
A container is an ordinary Linux process fenced in by namespaces (what it can see), cgroups (how much it can use) and its own filesystem unpacked from an image.
A container is a normal process with three fences around it. The two models below show what a container sees (its own process list) and what it may use (a memory limit), then the real thing.
Example 1 · A model of the PID namespace
import java.util.ArrayList;import java.util.List;
record HostProcess(int hostPid, String command, String container) {}
public class NamespaceDemo { static void showHostView(List<HostProcess> all) { System.out.println("Host sees:"); for (HostProcess p : all) { System.out.println(" PID " + p.hostPid() + " " + p.command()); } }
static void showContainerView(List<HostProcess> all, String container) { System.out.println("Inside " + container + ":"); int pidInside = 1; for (HostProcess p : all) { if (container.equals(p.container())) { System.out.println(" PID " + pidInside + " " + p.command()); pidInside++; } } }
public static void main(String[] args) { List<HostProcess> all = new ArrayList<>(); all.add(new HostProcess(1, "systemd", null)); all.add(new HostProcess(812, "dockerd", null)); all.add(new HostProcess(4127, "java -jar shoplite-api.jar", "shoplite-api")); all.add(new HostProcess(4301, "mysqld", "shoplite-db")); all.add(new HostProcess(4355, "sh", "shoplite-api"));
showHostView(all); showContainerView(all, "shoplite-api"); showContainerView(all, "shoplite-db"); }}Host sees: PID 1 systemd PID 812 dockerd PID 4127 java -jar shoplite-api.jar PID 4301 mysqld PID 4355 sh Inside shoplite-api: PID 1 java -jar shoplite-api.jar PID 2 sh Inside shoplite-db: PID 1 mysqld
What this code does
- The host keeps one real process list. Each
HostProcessremembers which container (if any) it belongs to. showContainerViewshows only that container's processes and numbers them from 1, which is what the PID namespace does.- So the ShopLite JVM is PID 4127 to the host but PID 1 inside its container, and it cannot see
mysqldat all.
Example 2 · The real thing: ps inside a container
Runs in: a terminal with Docker installed
# alpine is a tiny Linux image; ps lists the processes it can seedocker run --rm alpine:3.20 psPID USER TIME COMMAND
1 root 0:00 psWhat this code does
- The container sees exactly one process,
psitself, and it is PID 1. Every other process on your computer is hidden by the PID namespace. - You will run commands like this after the install lesson;
--rmdeletes the stopped container afterwards.
Example 3 · A model of a cgroup memory limit
class MemoryLimit { private final int limitMb; private int usedMb;
MemoryLimit(int limitMb) { this.limitMb = limitMb; }
boolean allocate(int mb) { if (usedMb + mb > limitMb) { return false; } usedMb += mb; return true; }
int usedMb() { return usedMb; }}
public class CgroupDemo { public static void main(String[] args) { MemoryLimit limit = new MemoryLimit(512); // like docker run --memory 512m int[] requests = {128, 128, 128, 64, 128};
for (int i = 0; i < requests.length; i++) { int mb = requests[i]; if (limit.allocate(mb)) { System.out.println("Step " + (i + 1) + ": +" + mb + " MB, using " + limit.usedMb() + " of 512 MB"); } else { System.out.println("Step " + (i + 1) + ": +" + mb + " MB would exceed 512 MB"); System.out.println("Kernel kills the process: exit code " + (128 + 9)); break; } } }}Step 1: +128 MB, using 128 of 512 MB Step 2: +128 MB, using 256 of 512 MB Step 3: +128 MB, using 384 of 512 MB Step 4: +64 MB, using 448 of 512 MB Step 5: +128 MB would exceed 512 MB Kernel kills the process: exit code 137
What this code does
MemoryLimitplays the role of a cgroup with a 512 MB limit, like starting a container with--memory 512m.- Step 5 would go over the limit. The real kernel does not throw a Java exception here: it kills the process, and Docker reports exit code 137, which is 128 + 9 (signal 9, SIGKILL).
- Exit code 137 is a common sight later in the course: it usually means "out of memory in the container".
The three fences:
- Namespaces: what the process can see (processes, network, hostname, mounts).
- cgroups (control groups): how much the process can use (memory, CPU).
- Own filesystem: the files the process gets, taken from the image.
Because of the PID namespace, the first process in a container sees itself as PID 1 (process id 1), even though the host knows it by another number such as 4127.
Predict the output
Predict what a container sees
Choose what happens in each situation.
Round 1 of 2
What process number does the ShopLite JVM see for itself inside its container?
Start-up time, size and density
Density is how many copies of an app fit on one server. A VM pays for a guest OS in every copy, so far fewer VMs fit than containers.
Starting a VM boots a whole operating system; starting a container starts one process. The program below counts how many ShopLite copies fit on a 16 GB server both ways.
Example 4 · How many ShopLite copies fit on one server
record Option(String name, int overheadMb, int startSeconds) {}
public class DensityDemo { static final int SERVER_MB = 16 * 1024; static final int RESERVED_MB = 1024; static final int APP_MB = 512; // one ShopLite API instance
public static void main(String[] args) { Option[] options = { new Option("Virtual machine", 1024, 45), // full guest OS per copy new Option("Container", 20, 2) // shares the host kernel }; int free = SERVER_MB - RESERVED_MB; for (Option o : options) { int perCopy = APP_MB + o.overheadMb(); int copies = free / perCopy; System.out.printf("%-15s %4d MB each -> %2d copies, about %d s to start%n", o.name(), perCopy, copies, o.startSeconds()); } }}Virtual machine 1536 MB each -> 10 copies, about 45 s to start Container 532 MB each -> 28 copies, about 2 s to start
What this code does
- Each VM copy pays 1024 MB for its guest OS on top of the 512 MB app; a container pays about 20 MB.
- On the same 16 GB server that is 10 VMs against 28 containers. Integer division (
free / perCopy) drops the part that does not fit. - The numbers are rough, typical values for teaching. Real overhead depends on the OS image and settings.
A VM takes tens of seconds to minutes to start, a container usually well under a second (a Spring Boot app still needs a few seconds of its own).
Typical numbers, which vary a lot with the setup:
- Disk size: VM image often several GB; container image tens to a few hundred MB.
- Memory overhead: VM often 512 MB to 1 GB+ for the guest OS; container a few MB.
- Density: a handful of VMs per server; tens of containers per server.
Docker on Windows and macOS runs a small Linux VM
WSL 2 is a light Linux virtual machine built into Windows, with a real Linux kernel. Docker Desktop uses it to run Linux containers on Windows.
Linux containers need a Linux kernel, and Windows and macOS do not have one. So Docker Desktop quietly starts one small Linux VM and runs every container inside it.
Example 5 · Proof of the hidden Linux VM
Runs in: a terminal with Docker Desktop installed on Windows
# Which kernel does a container see?docker run --rm alpine:3.20 uname -sdocker run --rm alpine:3.20 uname -rLinux 6.6.87.2-microsoft-standard-WSL2
What this code does
- Even on a Windows laptop the container reports
Linux: it runs on the Linux kernel inside the WSL 2 VM. Themicrosoft-standard-WSL2part names that kernel. - On a Mac the second line shows a Docker Desktop kernel such as
6.10.14-linuxkit. Your version numbers will differ.
On Windows that VM is usually WSL 2. On macOS Docker Desktop starts its own small Linux VM using Apple's virtualization support. You only see the docker command; the VM is managed for you.
Order of execution
Where a container really runs on Windows
Put the steps in the order they happen.
When a virtual machine is still the right choice
Isolation is how well one running program is kept apart from the others. A VM isolates strongly because each has its own kernel; containers share one kernel, so their wall is thinner.
Containers do not replace VMs everywhere. A VM is the better tool for a different kernel, strong isolation or an old app tied to a full operating system. The helper below applies that rule.
Example 6 · VM or container? A small decision helper
record Need(String app, boolean needsOtherKernel, boolean untrustedCode, boolean legacyOs) {}
public class ChooserDemo { static String choose(Need n) { if (n.needsOtherKernel()) { return "VM (needs a different kernel)"; } if (n.legacyOs()) { return "VM (needs a full old operating system)"; } if (n.untrustedCode()) { return "VM (needs strong isolation)"; } return "Container"; }
public static void main(String[] args) { Need[] needs = { new Need("ShopLite API (Java 17)", false, false, false), new Need("MySQL 8.4 for dev", false, false, false), new Need("Old Windows billing app", true, false, true), new Need("Students' uploaded code", false, true, false) }; for (Need n : needs) { System.out.println(n.app() + " -> " + choose(n)); } }}ShopLite API (Java 17) -> Container MySQL 8.4 for dev -> Container Old Windows billing app -> VM (needs a different kernel) Students' uploaded code -> VM (needs strong isolation)
What this code does
- Each
Needrecord holds the three questions from this section: other kernel, untrusted code, legacy OS. choosechecks them in order and returns the first reason that forces a VM; otherwise a container is enough.- ShopLite and its MySQL database are ordinary Linux apps, so they go in containers, which is the plan for the rest of this section.
Pick by the need:
- Different operating system or kernel: VM.
- Untrusted code from outside users: VM (or a container with an extra sandbox).
- An old app tied to a full old OS: VM.
- Your own Linux apps such as ShopLite and MySQL: container.
In practice the two work together: cloud servers are usually VMs, and companies run containers inside those VMs.
Next step
Check your understanding
11 quick questions