AlgoViz

Docker

easy 26 min

Docker packages a program with its files into an image and runs it as an isolated process called a container.

Video lesson · Chapter 1 of 5

What starts when the bakery opens?

0:00 / 4:10

Docker in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Docker is a set of tools to build, share and run containers. An image is a read-only package: your program, its libraries and settings. A container is a running process that sees the image as its own file system and is separated from other processes on the same machine.

A container is not a small virtual machine. It has no kernel of its own. It is a normal Linux process that the host's kernel shows a private view of the world, with limits on what it may use.

Why it exists

Programs depend on versions of libraries, files in certain places, and settings. When those differ between a laptop and a server, the program breaks. An image carries everything above the kernel, so the same bytes that passed the tests run in production.

Starting a process is much cheaper than starting an operating system. So many containers fit on one machine, they start quickly, and a new version is simply a new image.

A short history

  1. March 2013

    Solomon Hykes shows Docker to the public in a talk at PyCon.

  2. 22 June 2015

    Docker, CoreOS and others start the Open Container Initiative under the Linux Foundation, to standardise image and runtime formats.

  3. 29 March 2017

    containerd, Docker's core runtime, joins the Cloud Native Computing Foundation.

  4. 2023

    Docker Engine 23.0 makes BuildKit with Buildx the standard builder on Linux.

  5. Engine 29

    The containerd image store becomes the default on fresh installations.

Words to know

Image
A read-only package of layers plus settings, named by tag or digest.
Container
An isolated process with a thin writable layer above an image.
Layer
The file changes of one build step, identified by a hash.
Registry
A server that stores images, such as Docker Hub.
Namespace
A kernel feature that gives a process its own view: processes, network, files.
cgroup
A kernel feature that limits and counts CPU, memory and process numbers.
Volume
Storage that outlives the container.
OCI
Open standards for images and runtimes, so other tools can run Docker images.

How it works

Step through the idea, or press Play.

Step 1 of 3

Build an image. Each file-changing instruction adds a layer

Understand it

Start here

Stackable lunch tins

A canteen packs lunch in tins that stack: rice below, vegetables above, curry on top. The tins are closed and never change. Each guest gets only one thin lid of their own to put things on.

The lunch tins
RICEVEGCURRYThree tins make one lunch

If the rice tin changed, every tin above would have to be packed again.

Why

What it gives you

  • Same everywhere

    The image that passed the tests is the one that runs. No more differences in libraries.

  • No conflicts

    One program with Python 3.12 and another with 3.14 run side by side.

  • Fast starts

    Only a process starts; no guest system boots. New copies and recovery are quick.

  • Dense

    No operating system per program, so one machine runs more of them. How many depends on the programs.

  • One pipeline

    Build once, promote the same digest through test, staging and production.

  • Service borders

    Each service ships with its own dependencies and its own release.

Inside

What happens on docker run

The engine

A developer's docker command calls dockerd inside one thick box, the Docker host. dockerd asks containerd, which asks runc, which starts two containers. dockerd pulls images from a registry outside the host.
runc sets a container up and exits. A small shim process stays with each container.
  1. 1

    The command

    docker run nginx becomes a request to the daemon's REST API, normally over the Unix socket /var/run/docker.sock.

  2. 2

    Is the image here?

    The daemon looks for the name and tag locally; without a tag, latest is meant.

  3. 3

    Pull

    Missing layers are downloaded from the registry over HTTPS, several at once, and checked against their SHA-256 digests. Shared layers are not downloaded again.

  4. 4

    Create

    An identifier, the settings, and a writable layer above the image, joined by a union file system such as OverlayFS.

  5. 5

    Network

    A virtual cable joins the container to a bridge with an address, often from 172.17.0.0/16. Firewall rules translate published ports.

  6. 6

    Mounts

    Volumes are created if needed and mounted; bind mounts show a host directory; tmpfs lives in memory.

  7. 7

    Start

    dockerd calls containerd over gRPC; containerd uses runc with an OCI description.

  8. 8

    Isolate

    runc creates namespaces, applies cgroups, capabilities and the seccomp filter, then starts your program as process 1.

Who calls whom

Kernel parts of a container

PartGivesExample
PID namespaceOwn process listProcess 1 inside, 45892 on the host
NET namespaceOwn interfaces and portsTwo containers both listen on 80
MNT namespaceOwn file system viewThe image as /
UTS, IPCOwn host name, shared memoryhostname differs
USER namespaceOwn user numbersNot on by default; use rootless mode or userns-remap
cgroupsLimits and accounting512 MB, half a CPU
Capabilities, seccompFewer powers, fewer system callsThe default filter blocks about 44 of over 300 calls

Layers

Images, layers and copy on write

Instructions that change files (RUN, COPY, ADD) add a layer. Others, such as ENV, CMD or EXPOSE, only change settings. Layers are named by the hash of their content, so identical layers are stored and sent once. Reading looks from the top layer down. Writing copies the file up into the container's own layer first. Deleting writes a marker that hides the file; the bytes below remain.

Disk used by many containers

S=∑u ∈ unique layerssu+∑c=1nwc300+20×5=400 MB, not 20×305=6,100S = \sum_{u\,\in\,\text{unique layers}} s_u + \sum_{c=1}^{n} w_c \qquad 300 + 20 \times 5 = 400\text{ MB, not } 20 \times 305 = 6{,}100
Example: 20 containers of one 300 MB image, each writing 5 MB.
Text
# bad: the package lists stay in the first layerRUN apt-get update && apt-get install -y curlRUN rm -rf /var/lib/apt/lists/*# good: created and deleted in one stepRUN apt-get update \ && apt-get install -y --no-install-recommends curl \ && rm -rf /var/lib/apt/lists/*
A delete in a later step saves nothing

Build

Fast builds: the cache

The builder reuses a step if its instruction and its input files are unchanged. Once one step changes, every step after it runs again. So put what rarely changes first: base, dependency list, install, then your code.

A code change, two Dockerfiles

Text
# syntax=docker/dockerfile:1FROM node:24 AS builderWORKDIR /appCOPY package.json package-lock.json ./RUN npm ciCOPY . .RUN npm run buildRUN npm prune --omit=devFROM node:24-alpineWORKDIR /appENV NODE_ENV=productionCOPY --from=builder --chown=node:node /app/dist ./distCOPY --from=builder --chown=node:node /app/node_modules ./node_modulesUSER nodeEXPOSE 3000CMD ["node", "dist/server.js"]
Multi-stage Dockerfile

A multi-stage build compiles in a large image and copies only the result into a small one. Pulls are faster and an intruder finds no compiler. Modules with native code must be built for the same C library as the final image: Debian images use glibc, Alpine uses musl. When in doubt use the same family in both stages.

More build habits

  1. 1

    Use .dockerignore

    Leave out node_modules, .git, .env, logs, coverage, Markdown and the Docker files themselves. Smaller context, fewer cache misses, no leaked secrets.

  2. 2

    Combine related steps

    Update, install and clean up in one RUN.

  3. 3

    Choose a small base

    Slim, Alpine or distroless. Fewer packages mean fewer vulnerabilities to patch.

  4. 4

    Pin versions

    Use a precise tag or a digest. latest moves. Rebuild regularly to receive security fixes.

Network

How containers talk

Two networks on one host

Inside one Docker host, users reach the web container on port 80 in the front network. The web container calls the API. The API belongs to both networks and calls the database and the cache in the back network.
The web container has no network in common with the database.
NetworkUseKnow this
User-defined bridgeThe normal choiceBuilt-in DNS: containers find each other by name
Default bridgeLegacyNo DNS by name; everything without --network lands here
hostHighest network speedNo isolation, no port mapping
noneJobs without networkLoopback only
overlaySeveral hostsPart of Swarm mode
macvlan, ipvlanOwn address in the local networkFor special cases

Data

Volumes and other mounts

KindWhereGood forExample
Writable layerIn the containerTemporary filesGone with docker rm
Named volumeManaged by DockerDatabases, uploads-v pgdata:/var/lib/postgresql
Bind mountA host directorySource code in development-v ./src:/app/src
Read-only mountEitherConfiguration-v ./conf:/app/conf:ro
tmpfsMemorySensitive scratch files--tmpfs /tmp
PostgreSQL 18 images keep data in a directory per major version, so the mount is the parent /var/lib/postgresql. For 17 and older it is /var/lib/postgresql/data.

Life of a container and its data

Stopping keeps the writable layer; removing deletes it. A named volume survives both.

A volume is not a backup. It sits on one host, can be deleted, and does not follow a container to another machine. For important databases a managed service or a careful operator is often simpler.

Limits

CPU, memory, health and logs

What --cpus means

quota=cpus×period0.5×100 ms=50 ms of CPU in every 100 ms\text{quota} = \text{cpus} \times \text{period} \qquad 0.5 \times 100\text{ ms} = 50\text{ ms of CPU in every } 100\text{ ms}
A busy container that has used its 50 ms waits for the next period. That is throttling, and it looks like latency.
SettingEffectDefault
-m 512mHard memory limit; above it the kernel kills a processNo limit
--memory-reservation=256mSoft limit under pressureNone
--cpus=0.5Share of CPU time, in coresNo limit
--pids-limit=100Number of processesNo limit on plain Docker
--restart=unless-stoppedStart again after a crash or rebootNo restart
HEALTHCHECKMarks healthy or unhealthyNone
docker stopSIGTERM, then SIGKILL10 seconds of grace on Linux
json-file logsStored on the hostNo rotation; set max-size
YAML
services:  api:    build: ./api    ports: ["127.0.0.1:3000:3000"]    environment:      DATABASE_HOST: db      DATABASE_PASSWORD_FILE: /run/secrets/db_password    secrets: [db_password]    depends_on:      db: { condition: service_healthy }    healthcheck:      test: ["CMD", "wget", "-qO-", "http://127.0.0.1:3000/health"]      interval: 30s      timeout: 10s      retries: 3      start_period: 40s    deploy:      resources:        limits: { cpus: "0.5", memory: 512M }        reservations: { cpus: "0.25", memory: 256M }    logging:      driver: json-file      options: { max-size: "10m", max-file: "3" }    networks: [backend]  db:    image: postgres:18    environment:      POSTGRES_DB: app      POSTGRES_PASSWORD_FILE: /run/secrets/db_password    secrets: [db_password]    volumes: ["pgdata:/var/lib/postgresql"]    healthcheck:      test: ["CMD-SHELL", "pg_isready -U postgres -d app"]      interval: 5s      retries: 10    networks: [backend]secrets:  db_password: { file: ./secrets/db_password.txt }volumes: { pgdata: {} }networks: { backend: {} }
compose.yaml

The old top-level version line is obsolete. depends_on alone waits only for a start; service_healthy needs a health check on the other service. Keep the secrets file out of Git and out of the image.

Security

Harden a container

  1. 1

    Image

    Small base, pinned, scanned in the pipeline (for example docker scout cves), rebuilt for fixes.

  2. 2

    User

    USER in the Dockerfile or -u 1000:1000. Root in a normal container is root's number on the host.

  3. 3

    Powers

    --cap-drop ALL, add back only what is needed, and --security-opt no-new-privileges.

  4. 4

    File system

    --read-only with a tmpfs for /tmp.

  5. 5

    Limits and network

    Memory, CPU and process limits; separate networks.

  6. 6

    The daemon

    The Docker socket is root on the host. Never mount it into a container you do not trust. Consider rootless mode.

Shell
docker run -d --read-only --tmpfs /tmp \  --cap-drop ALL --security-opt no-new-privileges \  -u 1000:1000 -m 512m --cpus=0.5 --pids-limit=100 \  myapp:1.0
A hardened run

Decide

Containers, virtual machines, and the rest

Container and virtual machine

ContainerVirtual machine
KernelShared with the hostIts own
BorderKernel featuresHypervisor and hardware
StartA process startA system boot
OverheadLittle above the processMemory and disk of a whole system
Other systemsSame kernel familyAny
Choose forServices, CI, many small programsUntrusted code, other systems, strict rules
Production often uses both: virtual machines separate customers, containers pack programs inside them. Docker Desktop on macOS and Windows runs Linux containers in a virtual machine.

What should run this?

Related tools

ToolSameDifferentChoose it for
PodmanCommands, images, volumesNo daemon, rootless by design, systemdLinux servers without a root daemon
KubernetesRuns the same imagesMany hosts, healing, rolling updates, scaling; uses containerd, not Docker EngineFleets of services
FirecrackerFast, denseMicroVM with its own kernel; boots in under 125 ms, under 5 MiB overheadMany customers on one machine
AWS Lambda and similarCan take an imageSomeone else runs itEvents and quiet services

Use Docker when

  • Services have different dependencies
  • A new developer should start with docker compose up
  • The same build must pass through all environments
  • Several programs share a host
  • Stateless services scale by copies

Think again when

  • State is complex: a managed database may be simpler
  • A legacy program depends on fixed paths or a desktop
  • One static program on one server: systemd is enough
  • Programs need different kernels
  • Every microsecond of network counts
  • You run untrusted code without another wall

Run

Commands you will use

GoalCommand
Build, pushdocker build -t myapp:1.0 ., docker push repo/myapp:1.0
Rundocker run -d -p 8080:80 nginx
Lookdocker ps -a, docker logs -f --tail 100 app
Go insidedocker exec -it app sh
Stackdocker compose up -d, docker compose logs -f api, docker compose down
Copiesdocker compose up -d --scale api=3 (no fixed host port)
Clean imagesdocker image prune; -a also unused tagged ones
Clean alldocker system prune
Clean volumesdocker volume prune removes unused anonymous ones; -a also named ones. Data is deleted

Summary

The whole topic in one minute.

An image is a stack of read-only layers; a container adds one thin writable layer and an isolated process. Namespaces decide what the process sees, cgroups decide how much it may use, and everyone shares the host's kernel.

Order the Dockerfile from what rarely changes to what often changes, build in one stage and ship another, keep data in volumes, put services on user-defined networks, set limits, and run without root. Use Compose on one machine and an orchestrator for many.

  • A container is a process; the kernel is shared.
  • Namespaces show less, cgroups allow less.
  • Images are shared read-only layers; each container adds one thin layer.
  • Order builds by change; ship a second, small stage.
  • Data in volumes, names through user-defined networks, secrets outside images.
  • Limits, rotation, health checks and a non-root user are not defaults: set them.

Sources