What's inside a Docker image

An image is a sealed box made of stacked layers. The order of lines in your Dockerfile decides how long a rebuild takes, and a deleted secret is still inside the image.

Part 2 of 9 · Containers5 min read
DockerfileFROM alpineCOPY deps.txt .RUN install depsCOPY . .one line = one layer1234alpine1deps.txt2deps3your code4container writes herereused from cachenothing changed hereredrawnonly the code changeddeps first, code lastso a code edit keeps the depskey.pemdeleted files still ship

In part 1 we ran alpine, and a Linux system answered in a fraction of a second. We opened the box and found one process at work. But that process read files: a shell, ps, a whole /bin. Where did those files come from? And why does the second docker build of a project finish almost at once, when the first one took minutes?

The packing list and the sealed box

We are back at the port. Before any box goes on a ship, someone packs it. If Bub packs from memory, every box is a little different. So he packs from a written list, and anyone who follows the list gets the same box.

That list is the Dockerfile. The result is an image, the sealed box. It holds your program, the libraries it needs and the parts of an operating system it expects to find.

A container is that box, opened and put to work. One image can start ten containers, and none of them can change the image.

base (debian)python 3.13pip install (13.8 MB)COPY . . (your code)writable layercontainerpython:3.13-slimread-only image
An image is a stack of read-only sheets. A running container adds one thin writable sheet on top.

Sheets of tracing paper

Bub does not pack the box as one solid block. He draws it on sheets of tracing paper, one sheet for each line of the list that changes files. Then he stacks the sheets. When you look down through the stack, you see one complete picture. Each sheet is a layer.

Here is a small packing list for a Python service:

FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "main.py"]

Put it in an empty folder. Next to it, add a requirements.txt that holds one line, requests==2.32.3, and a main.py that prints a greeting. Build the image and run it.

Shell
docker build -q -t shop .   && docker run --rm shop 
sha256:98302360b06fc1a9598cf89dc9f92b589dfa1fc571d49f4826dbdeb595c1f345
hello from the box

Here is what each marked part does:

  1. 1-q makes the build quiet, so it prints only the id of the new image.
  2. 2-t shop gives the image the name shop. The dot at the end is the build folder, where Docker looks for the Dockerfile.
  3. 3&& runs the second command only if the first one worked. docker run --rm shop then starts a container from the image and removes it at the end.

Now ask the image for its sheets, newest first.

Shell
docker history --format "{{.Size}}\t{{.CreatedBy}}" shop | head -6   
0B	CMD ["python" "main.py"]
20.5kB	COPY . . # buildkit
13.8MB	RUN /bin/sh -c pip install --no-cache-dir -r…
12.3kB	COPY requirements.txt . # buildkit
8.19kB	WORKDIR /app
0B	CMD ["python3"]

Here is what each marked part does:

  1. 1docker history lists the sheets of an image, newest first, one row for each sheet.
  2. 2--format "..." chooses the columns. {{.Size}} is the size of the sheet, {{.CreatedBy}} is the Dockerfile line that made it, and \t puts a tab between them.
  3. 3| head -6 passes the rows to head, which keeps only the first six.

The top five rows are our five lines. Four of them changed files and made sheets. CMD is a 0B entry with no sheet behind it. It is only a note on the box that says what to run. Below our rows come the rows of the python:3.13-slim image we started from, which brought its own stack. The top row of that stack is its own CMD ["python3"] note. The libraries are the heavy sheet at 13.8 MB, and our code is a few kilobytes. Your image ID and sizes will differ with the base image version and your machine.

When a container starts, Docker puts one more blank sheet on top for the container to write on. When the container is removed, Docker deletes only that sheet. Every container from the same image shares the sheets below.

The cache: redraw only what changed

Docker keeps each sheet after a build. On the next build, Docker reads the list line by line. If a line is the same as last time, and the files it reads have the same contents, Docker reuses the saved sheet. Timestamps do not matter. The store of saved sheets is the build cache.

The first changed line ends the reuse. Its sheet and every sheet above it are redrawn, because each sheet is drawn on top of the one below.

Add one line to main.py and build again.

Which steps say CACHED after changing only main.py?

Shell
echo 'print("one more line")' >> main.py 
time (docker build --progress=plain -t shop . 2>&1 | grep -E "/5\]|CACHED")   
#5 [1/5] FROM docker.io/library/python:3.13-slim@sha256:70729b46c69b4f1e97c4822c1af3df53a1476cf5ddc6c087c0c10bc3a5678c2f
#6 [2/5] WORKDIR /app
#6 CACHED
#7 [3/5] COPY requirements.txt .
#7 CACHED
#8 [4/5] RUN pip install --no-cache-dir -r requirements.txt
#8 CACHED
#9 [5/5] COPY . .

real	0m0.310s
user	0m0.070s
sys	0m0.057s

Here is what each marked part does:

  1. 1>> main.py adds the text to the end of the file main.py. This is the only change we make to the project.
  2. 2time ( ... ) runs the commands inside the parentheses and prints how long they took.
  3. 3--progress=plain prints every build step as plain lines. 2>&1 sends the error messages down the same pipe as the normal output.
  4. 4grep -E keeps only the lines that match the pattern. Here the pattern means either a step label such as [3/5], or the word CACHED.

Everything up to and including pip install came from the cache. Only the last COPY ran. Now change a dependency instead:

Shell
echo "six==1.17.0" >> requirements.txt  
time (docker build --progress=plain -t shop . 2>&1 | grep -E "/5\]|CACHED")
#5 [1/5] FROM docker.io/library/python:3.13-slim@sha256:70729b46c69b4f1e97c4822c1af3df53a1476cf5ddc6c087c0c10bc3a5678c2f
#6 [2/5] WORKDIR /app
#6 CACHED
#7 [3/5] COPY requirements.txt .
#8 [4/5] RUN pip install --no-cache-dir -r requirements.txt
#9 [5/5] COPY . .

real	0m5.044s
user	0m0.065s
sys	0m0.058s

Here is what each marked part does:

  1. 1six==1.17.0 is one line of a dependency list: the package name, ==, and the exact version to install.
  2. 2>> requirements.txt adds that line to the end of the file, so the list now has one more package.

The copy of requirements.txt changed, so pip install and everything above it ran again. The build took about five seconds instead of a third of a second. The timings depend on your machine and network, but the gap between them stays.

FROMWORKDIRCOPY requirements.txtRUN pip installCOPY . .first buildFROMCACHEDWORKDIRCACHEDCOPY requirements.txtCACHEDRUN pip installCACHEDCOPY . .rebuiltmain.py changedFROMCACHEDWORKDIRCACHEDCOPY requirements.txtrebuiltRUN pip installrebuiltCOPY . .rebuiltrequirements.txt changed

First build: every sheet is drawn and saved in the cache.

Put what changes least first

Now change the order. Copy the code first and install afterwards:

FROM python:3.13-slim
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -r requirements.txt
CMD ["python", "main.py"]

Save it as Dockerfile.wrong and build it once. Then change one line of main.py and build again.

Shell
echo 'print("just one line")' >> main.py
time (docker build --progress=plain -f Dockerfile.wrong -t shop:wrong . 2>&1 | grep -E "/4\]|CACHED")  
#4 [1/4] FROM docker.io/library/python:3.13-slim@sha256:70729b46c69b4f1e97c4822c1af3df53a1476cf5ddc6c087c0c10bc3a5678c2f
#6 [2/4] WORKDIR /app
#6 CACHED
#7 [3/4] COPY . .
#8 [4/4] RUN pip install --no-cache-dir -r requirements.txt

real	0m4.907s
user	0m0.073s
sys	0m0.061s

Here is what each marked part does:

  1. 1-f Dockerfile.wrong builds from the file Dockerfile.wrong instead of the file named Dockerfile.
  2. 2-t shop:wrong names the image shop and adds the tag wrong, so it does not replace our first image.

One changed line of code reinstalled every library. COPY . . now sits below pip install, and it changes on every edit. So the expensive sheet is redrawn every time. Two lines of requirements take five seconds. A real project with hundreds of requirements takes minutes, on every build.

Put what changes rarely, like dependencies, early in the file and low in the stack. Put what changes often, like your code, last.

code before depsdeps before codeFROMCACHEDWORKDIRCACHEDCOPY . .rebuiltRUN pip installrebuiltFROMCACHEDWORKDIRCACHEDCOPY requirements.txtCACHEDRUN pip installCACHEDCOPY . .rebuilt~5 s~0.3 sedit main.py
Code before dependencies: every edit redraws the install. Dependencies before code: an edit redraws only the code.

A deleted file is still in the box

Sheets only add. A later sheet cannot erase a mark on an earlier sheet. It can only paint over the mark. To delete a file, Docker puts a whiteout on the new sheet, and the whiteout hides the file.

Here is a packing list that writes a token and then removes it:

FROM alpine
RUN echo "token=sk_live_4f9a" > /secret.txt
RUN rm /secret.txt

Build it as leaky in its own folder. From inside a container, the file is gone:

Shell
docker build -q -t leaky . >/dev/null 
docker run --rm leaky cat /secret.txt 
cat: can't open '/secret.txt': No such file or directory

Here is what each marked part does:

  1. 1>/dev/null discards the normal output of the command, here the image id, so the screen stays clean.
  2. 2cat /secret.txt is the command that runs inside the container. It prints the file /secret.txt, and docker run ends when it ends.

Now unpack the image and read its sheets one by one. The loop matches the layout docker save writes on Docker Engine 25 and later.

Shell
mkdir layers && docker save leaky | tar -x -C layers  
for f in layers/blobs/sha256/*; do tar -tf "$f" 2>/dev/null | grep secret; done 
for f in layers/blobs/sha256/*; do tar -xOf "$f" secret.txt 2>/dev/null; done 
secret.txt
.wh.secret.txt
token=sk_live_4f9a

Here is what each marked part does:

  1. 1docker save leaky writes the whole image as one tar archive, which is a single file that holds many files.
  2. 2tar -x -C layers reads that archive from the pipe and unpacks it into the folder layers.
  3. 3tar -tf "$f" lists the names inside one sheet. 2>/dev/null hides the error for blobs that are not archives, and grep secret keeps the matching names.
  4. 4tar -xOf "$f" secret.txt prints the file secret.txt from the sheet to the screen. The capital O sends the file to standard output instead of to disk.

One sheet holds secret.txt. A later sheet holds the whiteout .wh.secret.txt. The token reads back in full, and anyone who can pull the image can do the same. docker history leaky even prints the token in the RUN command.

FROM alpinesecret.txttoken=sk_live_4f9a.wh.secret.txtRUN echoRUN rmwhiteoutstill in the image
The whiteout hides the file from the container. The sheet underneath still carries it to everyone who pulls the image.

Key points

  • An image is a read-only stack of layers, one per Dockerfile line that changes files. A container adds one writable layer on top.
  • On rebuild, Docker reuses every layer up to the first changed line and redraws everything above it.
  • Put dependencies before code, so an edit to the code does not reinstall the libraries.
  • Deleting a file in a later layer only hides it. Anything written to a layer ships with the image.

Next, in part 3: how the port’s depot finds a box, by its name and by its fingerprint.

New posts by email

One email when a post ships, about twice a month. Nothing else, and one click to leave.

Latest: Finding where a request breaks · RSS