Tech Interview RoomStudy guides

Docker

How do containers differ from virtual machines, and how do they work under the hood?

Intermediate · 2 min read · Lesson 1 of 6 in Docker

VMs vs containers

  • A VM virtualises hardware: a hypervisor runs full guest operating systems, each with its own kernel. Strong isolation, but gigabytes of overhead and boot times in seconds to minutes.
  • A container is an ordinary Linux process isolated by kernel features and sharing the host kernel. Megabytes of overhead, starts in milliseconds, dense packing. Isolation is weaker than a VM's because a kernel exploit affects every container on the host (sandboxes such as gVisor or Kata Containers and microVMs such as Firecracker add a stronger boundary).

The kernel building blocks

  • Namespaces give a process its own view of: process ids (pid), network interfaces and ports (net), mounts (mnt), hostname (uts), IPC, users (user) and cgroups.
  • cgroups limit and account resources: CPU shares and quotas, memory (exceeding it gets the process OOM-killed), I/O, number of processes.
  • Union / overlay filesystems (overlay2) stack read-only image layers with a thin writable layer per container.
  • Security: capabilities dropped by default, seccomp syscall filters, AppArmor or SELinux profiles.

Images and the ecosystem

  • An image is an ordered set of read-only layers plus metadata (entrypoint, environment, user), defined by the OCI image specification and addressed by a content digest. Layers are shared between images and cached.
  • The Docker CLI talks to dockerd, which uses containerd, which uses runc (the OCI runtime) to create the namespaces and cgroups. Kubernetes talks to containerd or CRI-O directly through the CRI; Docker itself is not required in clusters.

Follow-up questions interviewers ask

Try answering each one before you open it.

Why is a container not a security boundary in the way a VM is?

All containers share one kernel. A kernel vulnerability, a privileged container, a mounted Docker socket or excessive capabilities can let a process escape to the host and reach other containers. Mitigate with non-root users, dropped capabilities, read-only filesystems, seccomp profiles, user namespaces, and sandboxed runtimes (gVisor, Kata) for untrusted workloads.

What happens when you run `docker run nginx`?

The CLI sends the request to the daemon; the image is pulled layer by layer from the registry if not cached and unpacked into the content store; containerd prepares a snapshot (the image layers plus a writable layer) and an OCI runtime spec; runc creates the namespaces, cgroups and mounts and starts the entrypoint as PID 1 inside them; networking attaches a veth pair to the docker0 bridge with NAT for published ports.