Container vs VM

Container vs VM in DevOps Tools: --- Picture a city block that must house fifty families, and two ways to do it.


The Analogy: The Apartment Building and the Street of Detached Houses

Picture a city block that must house fifty families, and two ways to do it. The first is a street of fifty detached houses: each with its own foundation, its own furnace, its own water heater, electrical panel, and roof. Every house is complete and self-contained, answerable to nothing but itself -- but the street is mostly duplicated machinery, fifty furnaces heating fifty separate basements. The second is a single apartment building: one foundation, one central heating plant, one water main, one roof, subdivided into fifty units. The detached house is the virtual machine, carrying a full operating system of its own; the apartment is the container, sharing the building's services with every neighbor.

The apartment is still a real home. Behind the locked door of unit 4B is a private space: the family's own furniture, their own thermostat, their own mailbox, a meter that bills only what they use. A neighbor cannot wander in, cannot see the rooms, cannot draw on their electricity. The isolation is genuine even though the structure underneath is shared by everyone. This is precisely what a container gets from the kernel: a namespace that gives it a private view of processes, files, and network as if it were alone on the machine, and a cgroup that meters and caps the CPU and memory it may draw, so one tenant cannot starve the rest.

The shared building is exactly why the apartment is cheap and fast. A new family moves into a vacant unit in an afternoon, because the foundation, the heating, and the plumbing already exist -- they bring only furniture. Raising a new detached house takes months and a complete set of infrastructure. Fifty apartments amortize one furnace's fixed cost, so each additional family adds only their own rooms, never a whole basement. That is why a container starts in the time it takes to launch a process, and why a host packs containers far denser than it could pack VMs: the expensive shared parts, the kernel and the base system, are paid for once and once only.

But sharing cuts both ways, and the fourth truth is a warning. Because every unit rests on one foundation and draws from one water main, a crack in that foundation or a burst in that main can flood or condemn the entire building at once, where a single failing detached house leaves its forty-nine neighbors dry and warm. Weaker isolation is the standing price of shared services. And there is a subtler failure, one of accounting rather than engineering: the building manager who bills each of the fifty tenants for a full private foundation, furnace, and water main -- as if every apartment were a detached house -- reports the building as costing fifty times its true infrastructure. The shared parts get counted once per tenant instead of once for the whole building, and the grand total comes out wildly, confidently wrong. That is the exact mistake the disk-usage tool at the end of this lesson makes when it charges every container for the full image they all share.


Syntax or Core Structure

Three nouns carry the whole model. An image is a read-only template -- the recipe, built once and never mutated. A container is a running instance of an image, of which you can start many from one image at the same time. A registry is where images are stored and pulled from. The everyday commands map directly onto those nouns: pull an image, run a container from it, list what is running, remove what is not.

# pull a read-only image from a registry into the local store
docker pull api:v1

# run a container from that image; -d detaches, -p maps host:container ports
docker run -d -p 8080:80 api:v1

# list running containers; -a also shows stopped ones
docker ps -a

# stop a running container, then remove it
docker stop <id>
docker rm <id>

The one idea worth making concrete is the image/container split: the image is fixed, but each container is a separate living object with its own status. A tiny lifecycle model makes the distinction visible -- start three containers from one image, stop one, remove another, and list what remains:

class Engine:
    def __init__(self):
        self.images = {}
        self.containers = []
        self._n = 0
    def pull(self, name, size):
        self.images[name] = size
        print('pulled %s (%d MB)' % (name, size))
    def run(self, name):
        self._n += 1
        cid = 'c%d' % self._n
        self.containers.append([cid, name, 'Up'])
        print('started %s from %s' % (cid, name))
        return cid
    def stop(self, cid):
        for c in self.containers:
            if c[0] == cid:
                c[2] = 'Exited'
        print('stopped %s' % cid)
    def rm(self, cid):
        self.containers = [c for c in self.containers if c[0] != cid]
        print('removed %s' % cid)
    def ps(self, show_all=False):
        print('%-5s %-12s %s' % ('CID', 'IMAGE', 'STATUS'))
        for cid, img, st in self.containers:
            if show_all or st == 'Up':
                print('%-5s %-12s %s' % (cid, img, st))

e = Engine()
e.pull('api:v1', 200)
a = e.run('api:v1')
b = e.run('api:v1')
c = e.run('api:v1')
e.stop(b)
e.rm(c)
e.ps(show_all=True)

Output:

pulled api:v1 (200 MB)
started c1 from api:v1
started c2 from api:v1
started c3 from api:v1
stopped c2
removed c3
CID   IMAGE        STATUS
c1    api:v1       Up
c2    api:v1       Exited

One image, api:v1, produced three independent containers. Stopping c2 changed only its status, not the image and not its siblings; removing c3 dropped it from the list entirely. ps -a shows c1 still Up and c2 Exited but not yet removed -- a stopped container is a real object that still exists and still occupies disk until you rm it, which is the seed of the accounting problem this lesson ends on.


Technical Depth: Where the Isolation Boundary Sits

Two stacks, one shared layer

The difference between a VM and a container is exactly which layer they share and which they duplicate. A VM virtualizes the hardware: a hypervisor hands each guest a fake machine, and each guest boots a full operating system with its own kernel. A container virtualizes the operating system: the host kernel is shared, and each container gets only an isolated slice of it. Everything downstream -- boot time, size, density, blast radius -- follows from that single choice of boundary.

DimensionVirtual MachineContainer
Isolates atthe hardware (hypervisor)the OS (kernel namespaces)
Kernelits own, per guestshared with the host
Boot timetens of secondsprocess start, sub-second
Image sizegigabytestens to hundreds of MB
Density per hosttenshundreds
Blast radiusone guest, containedshared-kernel bugs reach across

The table's last two rows are a trade, not a free win. Containers pack denser and start faster precisely because they skip the per-instance kernel -- but skipping it is also why a kernel-level flaw is a shared-building problem, not a per-house one.

Density is a story about fixed cost, not per-instance cost

The headline "containers are lighter than VMs" is true only at scale, and seeing why requires the arithmetic. A VM pays a full guest OS for every instance; a container pays the host OS once and then only a small per-container overhead on top of the app. Model both as a fixed cost plus a per-instance cost and sweep the instance count:

GUEST_OS = 1024   # every VM carries its own OS
HOST_OS  = 1024   # shared once across all containers
APP      = 50     # the actual application
CTR_OVH  = 5      # per-container overhead

def vm_footprint(k):
    return k * (GUEST_OS + APP)

def container_footprint(k):
    return HOST_OS + k * (APP + CTR_OVH)

for k in (1, 10, 50):
    v = vm_footprint(k)
    cc = container_footprint(k)
    print('k=%-3d vm=%6d MB  container=%6d MB  ratio=%.1fx' % (k, v, cc, v / cc))

Output:

k=1   vm=  1074 MB  container=  1079 MB  ratio=1.0x
k=10  vm= 10740 MB  container=  1574 MB  ratio=6.8x
k=50  vm= 53700 MB  container=  3774 MB  ratio=14.2x

Look at k=1: a single container actually uses slightly more memory than a single VM here, because the shared host OS has not yet been amortized across anyone. The container's advantage is not that one container is cheaper than one VM -- it is that the expensive fixed cost (the OS) is paid once no matter how many containers you run. By k=10 the ratio is nearly 7x, and by k=50 it is over 14x, entirely because the VM column keeps multiplying its 1024 MB guest OS while the container column never does. Density, not per-instance weight, is the real argument for containers.


Real World Example: A Host Disk-Usage Estimator

A team runs a capacity dashboard that decides when a host needs more disk. Its estimator walks the running containers and, for each one, adds the size of the image it runs plus the container's own writable layer. That sounds right and reads cleanly, and it is wrong in the one way that matters. Here it is beside the correct version, both fed three containers started from a single 200 MB image, each having written 10 MB:

IMAGE = [('base', 120), ('deps', 60), ('app', 20)]
IMAGE_SIZE = sum(sz for _, sz in IMAGE)
WRITABLE = {'c1': 10, 'c2': 10, 'c3': 10}

def naive_disk():
    total = 0
    for cid, w in sorted(WRITABLE.items()):
        total += IMAGE_SIZE + w
    return total

def real_disk():
    return IMAGE_SIZE + sum(WRITABLE.values())

n = naive_disk()
r = real_disk()
print('containers=%d image=%d MB' % (len(WRITABLE), IMAGE_SIZE))
print('naive-estimate=%d MB' % n)
print('real-on-disk=%d MB' % r)
print('overcount=%d MB (%.1fx)' % (n - r, n / r))
print('check: real + (N-1)*image = %d' % (r + (len(WRITABLE) - 1) * IMAGE_SIZE))

Output:

containers=3 image=200 MB
naive-estimate=630 MB
real-on-disk=230 MB
overcount=400 MB (2.7x)
check: real + (N-1)*image = 630

The dashboard reports 630 MB used when the disk actually holds 230. The cause is copy-on-write, the mechanism that makes containers cheap: the image's layers are read-only and stored exactly once, and every container started from that image shares those same on-disk layers, adding only a thin writable layer of its own. So the real cost is one image plus the sum of the writable layers -- 200 + 10 + 10 + 10 = 230. The naive estimator instead pays for the image once per container, and the last output line names the damage exactly: naive = real + (N-1) * image. Those (N-1) extra copies of the image, here 2 * 200 = 400 MB, are pure phantom -- the building manager billing each tenant for a private foundation that in truth is poured once for the whole building.

The corrected real_disk is right for this scenario but should not be trusted past its assumptions, and the honest limits are worth stating. It presumes every container runs the same single image, which is why it can hard-code one IMAGE_SIZE; a real host runs containers from many different images whose layers partly overlap, and against that reality this function would undercount, because it has no way to see the other images at all. It counts only image layers and writable layers, ignoring logs and mounted volumes, which in production routinely dwarf the writable layer and are where disks actually fill. And the design flaw that survives even in the fixed version is that it models "the image" as one monolithic number instead of a set of content-addressed layers: two different images that share a common base layer should count that base once across both, which neither function here can express. The genuinely correct estimator is a set-union over distinct layer digests -- and until disk is accounted per layer rather than per image, you cannot answer the question the dashboard actually exists to answer, which is how much space a pull will consume or a prune will free.


Common Mistakes

  1. Thinking a container is a tiny VM. A container shares the host kernel; it is not a miniature guest OS. A Linux container needs a Linux kernel underneath -- it is an isolated process, not a virtualized machine, and treating it as the latter leads to every mistake below.
  1. Confusing the image with the container. The image is the read-only template; the container is a running instance of it. Changes made inside a running container do not alter the image and do not persist unless you deliberately rebuild or commit; editing a container is not editing its image.
  1. Expecting data to survive removal. A container's writable layer is destroyed when the container is removed. Anything not written to a mounted volume is gone on rm, so treating the writable layer as durable storage loses data on every redeploy.
  1. Counting shared image layers once per container. The exact estimator bug: N containers from one image cost image + N * writable, not N * (image + writable). Copy-on-write shares the read-only layers, so multiplying the image by the container count invents storage that is not there.
  1. Letting stopped containers pile up. A stopped container still exists and still holds its writable layer on disk. Plain ps hides them, so they accumulate invisibly; only ps -a reveals them, and only rm reclaims their space.
  1. Treating container isolation as equal to VM isolation. The shared kernel is a shared attack surface: a kernel exploit or a misconfigured privilege can cross the container boundary in ways a hypervisor resists. For hostile multi-tenant workloads, a container alone is a weaker boundary than a VM.
  1. Building a fat container that runs many services. Cramming an init system, an SSH daemon, and the app into one container recreates a VM and discards the model's benefits. A container should carry a single concern and let an orchestrator compose the rest.
  1. Believing the image pins everything. The image fixes userspace dependencies, but the kernel belongs to the host. Behavior sensitive to kernel version -- certain syscalls, cgroup v1 versus v2 -- can still differ between hosts even with an identical image.
  1. Judging efficiency from a single instance. At one instance a container and a VM are roughly comparable, as the density table's k=1 row shows. The container win appears only at scale, so benchmarking one container against one VM measures the wrong thing entirely.

Best Practices

  • Put one concern in each container and let an orchestrator compose them, rather than stuffing a whole stack into one image and losing the density and isolation the model exists to give.
  • Treat images as immutable, versioned artifacts: rebuild to change them, and never let "mutate a running container and snapshot it" become your delivery workflow.
  • Persist all durable state in named volumes, never in a container's writable layer, so removing or replacing a container never means losing data.
  • Account for disk by distinct layers and volumes, not by container count times image size, so capacity planning reflects what copy-on-write actually stores.
  • Prune stopped containers and dangling images on a schedule, and use ps -a and image ls to see the real footprint rather than the running-only view.
  • Pin base images to exact tags or digests so the read-only layers the whole fleet shares are reproducible and the shared cost is stable across builds.
  • Do not rely on containers as the sole security boundary for untrusted multi-tenant code; add a stronger boundary such as a microVM when the shared kernel is the risk you cannot accept.
  • Keep images small with a lean base and few layers, because that shared read-only cost is paid once for the whole host and every megabyte multiplies across the fleet's density.

Practice Exercises

  1. Extend the lifecycle Engine with a per-container log size and a df method that reports image-once + sum(writable) + sum(logs). Run four containers with differing log sizes and hand-check the reported total against your own sum.
  1. Prove the overcount formula. Show algebraically that naive_disk - real_disk = (N-1) * image for any container count N, then compute the phantom overcount for ten containers of the 200 MB image.
  1. Model two images that share a common 120 MB base layer. Write a disk function keyed by distinct layer name so the shared base is counted once across both images, and contrast its total with naively summing each image's full size.
  1. Using the density model, solve for the smallest instance count k at which the container footprint first drops below half the VM footprint, then plug that k back into both functions to verify the crossover.