# Containers: what they are and why they won

What a container really is, why "it works on my machine" stopped being an excuse, how containers differ from VMs and bare metal, and where Docker and OCI fit.

Course: [Docker](https://devops.rajeev.pro/courses/docker), lesson 1. About 20 minutes, beginner. Source: https://devops.rajeev.pro/courses/docker/01-why-containers

## What you will learn

- Explain what a container is in one sentence, without the word "lightweight VM"
- Name the problems containers solve for developers and for operations
- Compare bare metal, virtual machines and containers, and pick the right one for a job
- Explain what Docker is, and what OCI means for the images you build

## "It works on my machine"

**How software was shipped before containers.** Picture a small team in 2012. A developer
finishes a feature on her laptop. To get it onto the server, she writes a README:

1. Install Python 3.10.
2. Install these 14 libraries, at these exact versions.
3. Install the PostgreSQL client and ImageMagick from the system package manager.
4. Set these 6 environment variables and copy this config file to `/etc/app/`.

Someone in operations follows the README on the server, by hand. The app crashes.

**Why it kept going wrong.** The server isn't the laptop. It has Python 3.12 because another app
needed it. One library installed a newer version than the README said. ImageMagick is configured
differently. Each difference is small, but together they mean the code isn't running in the
environment it was tested in. Every team lost days to this, and "it works on my machine" became
a joke because everyone had said it. Worse, every server slowly drifted: after a year of manual
fixes, no two servers were quite the same, and nobody could rebuild one from scratch with
confidence.

**What containers changed.** Instead of shipping the code plus a list of instructions, you ship
the code **together with everything it needs**: the language runtime, the libraries, the system
tools and the default config, packed into one file called an **image**. The server no longer
needs Python or ImageMagick installed. It only needs Docker.

**How that fixes the problem.** An image is built once, from a recipe (a `Dockerfile`), and then
never changes. The exact image you tested on your laptop is the one that runs in CI, on the
staging server and in production. If it works in one place, it works the same way everywhere,
because it carries its environment with it.

That one property changes a lot:

- **Developers** stop writing "install these 14 things" in the README. `docker run` is the setup.
- **Operations** gets one way to run every app, whatever language it's written in.
- **Pipelines** build one artifact and deploy it everywhere, as the CI/CD course explains.
- **Density.** Many isolated apps can share one server without fighting over library versions.

In this lesson you'll see what a container really is under the hood, how it differs from a
virtual machine, and where Docker fits among the tools that run containers.

> **Video.** [Docker in 100 Seconds](https://www.youtube.com/watch?v=Gjnup-PuquQ) (Fireship)

## What a container actually is

A container is **a normal Linux process that the kernel isolates**. It's not a small VM and
there's no second operating system inside it.

A good picture is a block of flats. All the flats share one building, its foundation, water and
power: that's the host's **kernel**, the core of the operating system. But each flat has its own
front door and walls, so tenants can't see into each other's rooms. And each flat has its own
electricity meter, so one tenant can't use all the power. Two kernel features give a process
exactly that:

- **Namespaces** change what the process can **see**: its own process list, its own network interfaces, its own hostname and its own filesystem.
- **cgroups** limit what it can **use**: how much CPU, memory and I/O.

The filesystem comes from the **image**: a read-only stack of layers holding the app and its
dependencies. When a container starts, it gets a thin writable layer on top, which disappears
when the container is removed.

You can see the isolation yourself:

```sh
$ docker run --rm alpine ps              # the process list inside a new container
PID   USER     TIME  COMMAND
    1 root      0:00 ps
$ docker run --rm alpine cat /etc/os-release | head -n 2
NAME="Alpine Linux"
ID=alpine
```

Inside the container, `ps` is PID 1 and sees nothing else on your machine, and the filesystem
is Alpine Linux, whatever your host runs. `--rm` deletes the container when it exits, so you
don't collect stopped containers while you experiment.

## Bare metal, VMs and containers

Containers are the third step in how we share servers, and each step fixed a problem of the one
before.

- **Bare metal.** One physical server ran one main application. It was simple, but wasteful: many
  servers sat mostly idle, and a new server took weeks to order and set up.
- **Virtual machines.** A **hypervisor** split one physical server into several virtual ones,
  each with its own full operating system. Far less waste, but every VM carries a whole OS:
  gigabytes of disk, its own memory and a boot time of a minute or more.
- **Containers.** Apps share the host's operating system kernel and are only isolated from each
  other. No second OS to boot, so a container starts in well under a second and weighs megabytes.

The diagram and table compare all three:

> **Figure.** Three stacks compared. Bare metal: one operating system and its apps on the hardware. Virtual machines: a hypervisor runs several guest operating systems, each with its own kernel and apps. Containers: one host operating system and a container runtime run several isolated apps that share the host kernel.
>
> A VM virtualises the hardware and brings its own kernel. A container isolates processes on the one kernel the host already has.

|              | Bare metal                  | Virtual machine                         | Container                                 |
| ------------ | --------------------------- | --------------------------------------- | ----------------------------------------- |
| What you get | A whole physical server     | A full OS with its own kernel           | Isolated processes on the host kernel     |
| Starts in    | Minutes (boot the hardware) | Tens of seconds to minutes              | Usually under a second                    |
| Size         | The whole machine           | Gigabytes                               | Megabytes to a few hundred MB             |
| Isolation    | Complete                    | Strong: separate kernels                | Good, but one shared kernel               |
| Use it for   | Databases, raw performance  | Different OSes, strong tenant isolation | Apps and services, CI jobs, microservices |

They aren't rivals. In the cloud you'll nearly always run **containers inside VMs**: the VM
gives you strong isolation from other customers, and containers let you pack many apps onto it.

> **On a Mac or Windows.** Containers need a Linux kernel, so Docker Desktop quietly runs a small Linux VM and your containers run inside it. That's why `uname -r` in a container shows a different kernel from your Mac's. On a Linux server there's no VM: the container uses the host's kernel directly.

## Docker and OCI

**Docker** made containers easy in 2013 with three ideas: a simple file to describe an image
(the `Dockerfile`), a command line that builds and runs it (`docker build`, `docker run`), and a
registry to share images (Docker Hub). The kernel features existed before; Docker made them
usable.

Under the hood, Docker is several pieces:

| Piece                     | Does                                                        |
| ------------------------- | ----------------------------------------------------------- |
| `docker` CLI              | What you type. Sends requests to the engine                 |
| Docker Engine (`dockerd`) | Builds images, manages containers, networks and volumes     |
| containerd                | Runs and supervises containers. Kubernetes uses it directly |
| runc                      | Talks to the kernel to create the namespaces and cgroups    |

The **Open Container Initiative (OCI)** turned the image format and the runtime into open
standards. That's why an image you build with Docker also runs on Podman, on containerd, on
Kubernetes and on every cloud container service. Learn Docker and you've learned how containers
work everywhere.

```sh
$ docker run hello-world
Hello from Docker!
This message shows that your installation appears to be working correctly.
...
$ docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
alpine        latest    ...            ...            ~8MB        # yours will differ a little
hello-world   latest    ...            ...            a few kB
```

> **A shared kernel is a shared risk.** Containers are isolated, but not as strongly as VMs: a kernel bug can let a process escape. Don't run containers as root unless you need to, and don't run untrusted images. The *Security* stage of this course covers how.

> **In production.** Pin images to a version tag, like `node:22-alpine`, never just `latest`. `latest` is whatever was pushed most recently, so the same deploy can run different code on Monday and on Friday.

## Mission: Prove a container shares the host kernel

A teammate insists every container runs its own operating system, like a VM. Settle it on a Linux machine: record the host's kernel version and the kernel version seen from inside an Alpine container, side by side in one file.

- You need: A Linux host with Docker
- You'll have: ~/kernel-check.txt

```sh
$ echo "host:      $(uname -r)" > ~/kernel-check.txt
$ echo "container: $(docker run --rm alpine uname -r)" >> ~/kernel-check.txt
$ cat ~/kernel-check.txt
host:      6.8.0-48-generic
container: 6.8.0-48-generic
```

The numbers match because there's only one kernel. The container's files say Alpine, but the
kernel underneath is the host's. On Docker Desktop you'll see the kernel of its Linux VM
instead, which proves the same point.

## Try it

- Install Docker Desktop or Docker Engine, then run `docker run hello-world` and read what it says it did.
- Run `docker run --rm alpine cat /etc/os-release` and compare it with `cat /etc/os-release` on your machine.
- Run `docker run --rm alpine ps` and note the process with PID 1.
- Run `docker images` and find how big the alpine image is.
- Do the mini mission and keep `~/kernel-check.txt`.

## Quiz

1. What does every container on a Linux host share with the host?
   - Nothing, each one has its own kernel
   - **The host's kernel** (answer)
   - The host's filesystem and installed packages
   Why: A container is a set of isolated processes on the host's kernel. It brings its own filesystem from the image, but there is only one kernel, which is why containers start in a fraction of a second.

2. You need to run an app that requires a Windows kernel, on a Linux server. What do you reach for?
   - A container built from a Windows image
   - **A virtual machine running Windows** (answer)
   - A bigger container
   Why: Containers share the host kernel, so a Linux host can't run a Windows-kernel container. A VM brings its own kernel, so it can run any operating system.

3. What is the difference between an image and a container?
   - They're the same thing
   - **An image is the read-only template; a container is a running (or stopped) instance of it** (answer)
   - A container is a compressed image
   Why: Think class and object. One image can start many containers, and each container gets its own thin writable layer on top.

4. Why can Podman and Kubernetes run an image you built with Docker?
   - They all contain a copy of Docker
   - **Docker images follow the OCI image specification, an open standard every major tool supports** (answer)
   - They can't; you have to rebuild the image for each one
   Why: The Open Container Initiative defines the image format and runtime behaviour. Build once with any OCI tool and run it anywhere that speaks OCI.

## Resources

- [What is a container?](https://www.docker.com/resources/what-container/) (Docker)
- [Docker overview](https://docs.docker.com/get-started/docker-overview/) (Docker Docs)
- [Install Docker Engine on Linux](https://docs.docker.com/engine/install/) (Docker Docs)
- [Docker Desktop](https://docs.docker.com/desktop/) (Docker Docs)
- [Open Container Initiative](https://opencontainers.org/) (OCI)
- [OCI image specification](https://github.com/opencontainers/image-spec) (OCI on GitHub)
- [namespaces(7): the kernel feature behind isolation](https://manpages.ubuntu.com/manpages/noble/man7/namespaces.7.html) (Ubuntu manpages)
