Course outline · 0% complete

0/29 lessons0%

Course overview →

Layers: how images are really stored

lesson 3-2 · ~13 min · 8/29

Images are stacks of layers

How images are stored sounds like trivia, but it decides two things you feel every day: how long docker build takes (next lesson) and how long every push, pull, and deploy takes (unit 6). An image is not one big blob. Each instruction in your Dockerfile from lesson 3-1 produces a layer: a read-only diff containing only what that instruction changed.

  • FROM python:3.12-slim brings in the base layers (OS files + Python)
  • COPY requirements.txt . adds a tiny layer with one file
  • RUN pip install ... adds a layer with the installed packages
  • COPY . . adds a layer with your source code

The final image is just this stack read together. And when a container runs, Docker puts the thin writable layer from lesson 1-2 on top of the stack. Everything below stays read-only forever.

Why bother? Sharing. If ten of your images all start FROM python:3.12-slim, those base layers exist once on disk and once per download. Only each image's small unique layers differ.

each Dockerfile instruction adds a read-only layerFROM python:3.12-slim · base OS + PythonCOPY requirements.txt . · one small fileRUN pip install ... · installed packagesCOPY . . · your source codecontainer's writable layer (only at run time)
An image builds up as a stack of read-only layers, one per instruction. At run time a container adds a single writable layer on top, the same one you met in lesson 1-2.

Seeing the layers: docker history

The stack is not hidden, you can print it:

docker history myapp:v1
IMAGE          CREATED BY                                SIZE
8f3c2a91d0e4   CMD ["python" "server.py"]                0B
2b1a99c47f21   COPY . .                                  1.2MB
91c04d55ab02   RUN pip install -r requirements.txt      89MB
77e5301bfa6c   COPY requirements.txt .                   412B
...            FROM python:3.12-slim                     150MB

One row per instruction, newest on top, with the size each layer added. Engineers reach for this when an image is mysteriously huge: the SIZE column points at the guilty instruction. Here the pip install layer costs 89 MB, which is normal, but a 900 MB COPY . . row would mean junk files are being copied in (foreshadowing .dockerignore, next lesson).

Quiz

Ten different images on your machine all start with `FROM python:3.12-slim`. How many times are those base layers stored on disk?

Quiz

docker history shows your image's COPY . . layer is 850MB, while your source code is only 2MB. What most likely happened?

Problem

One word: what do we call the read-only diff that each Dockerfile instruction adds to an image?