Skip to content

Docker images and layers

Working knowledgeUnder the hood

Change one line of code and docker build reinstalls everything, or finishes in a second. Here is how an image is built from layers, and why the order of your Dockerfile decides what the cache can reuse.

01 One changed line, a full reinstall

You fix a typo in your code and run docker build. Instead of finishing in a second, it downloads and installs every dependency again. Move two lines in the Dockerfile and the same rebuild takes almost no time. To see why, you need to know what an image is made of.

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

02 An image is a stack of layers

Each instruction that changes files (RUN, COPY, ADD) produces a layer: an archive of just the files that step added, changed or deleted. Instructions such as CMD, ENV and EXPOSE only change the image’s settings and add no files. An image is the ordered list of its layers plus those settings.

An image is read-only layers; a container adds one writable layer on top
Running container
writable layertop
your code
pip packages
Python install
base OS files
  • image layer, read-only
  • this container only

The container sees one merged filesystem. A file in a higher layer hides the same path below it.

When a container starts, a union filesystem (overlayfs on most Linux hosts) stacks the layers and puts one empty writable layer on top. Reads fall through to the highest layer that has the file. The first write to a file copies it up into the writable layer. Image layers never change, so ten containers from one image share them on disk, and images built on the same base share the base layers.

03 How the build cache decides

Before running an instruction, the builder looks for a layer it made earlier from the same parent layer and the same instruction. For RUN, “same” means the same command text; the builder does not check whether the command would now give a different result. For COPY and ADD, it also compares a checksum of the files’ contents (not their timestamps). A match is a hit; the old layer is reused.

The parent is part of the key, so a miss is contagious: once one step rebuilds, every step below it has a new parent and rebuilds too. Watch the Dockerfile above after a one-line edit.

Rebuild after editing app.py: dependencies after code
Step 1 of 6
Rebuilt 0
Dockerfile
FROM python
WORKDIR /app
COPY . .
RUN pip install
CMD python
Image being built
Empty
  • cache hit, reused
  • cache miss, rebuilt
  • config only, no layer
  • not reached yet

You changed one line in app.py and run docker build again. The builder goes through the Dockerfile top to bottom, checking its cache at each instruction.

0 cache hits

The fix is to order steps from what changes least to what changes most. Dependencies change rarely, so copy only the file that lists them, install, and copy the rest of the code last.

The same edit with the dependency file copied first
Step 1 of 7
Rebuilt 0
Dockerfile
FROM python
WORKDIR /app
COPY reqs.txt
RUN pip install
COPY . .
CMD python
Image being built
Empty
  • cache hit, reused
  • cache miss, rebuilt
  • config only, no layer
  • not reached yet

Same edit to app.py, but this Dockerfile copies requirements.txt on its own first and installs packages before copying the rest of the code.

0 cache hits
Code before deps
FROM python:3.12-slim
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -r requirements.txt
CMD ["python", "app.py"]
Deps before code
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "app.py"]

The same pattern works for any language: package.json and package-lock.json before npm ci, go.mod and go.sum before go mod download, pom.xml before fetching Maven dependencies.

04 See it yourself

With BuildKit (the default builder in current Docker), --progress=plain prints every step, and the ones that hit the cache say CACHED. This is the second Dockerfile after editing app.py (trimmed):

Text
$ docker build --progress=plain -t myapp .
#5 [1/5] FROM docker.io/library/python:3.12-slim@sha256:aa94…
#7 [2/5] WORKDIR /app
#7 CACHED
#6 [3/5] COPY requirements.txt .
#6 CACHED
#8 [4/5] RUN pip install --no-cache-dir -r requirements.txt
#8 CACHED
#9 [5/5] COPY . .
#9 DONE 0.0s

docker history lists an image’s layers, newest first, with the instruction that made each one. The lines below your own come from the base image. Your sizes will differ.

Text
$ docker history myapp --format 'table {{.CreatedBy}}\t{{.Size}}'
CREATED BY SIZE
CMD ["python" "app.py"] 0B
COPY . . # buildkit 16.4kB
RUN /bin/sh -c pip install --no-cache-dir -r… 15.5MB
COPY requirements.txt . # buildkit 12.3kB
WORKDIR /app 8.19kB
CMD ["python3"] 0B

05 When it bites

Deleting a file in a later layer does not remove it from the image. The later layer only records a “whiteout” that hides the path; the bytes are still in the earlier layer, and anyone who pulls the image can extract them. That includes secrets.

COPY .env . RUN ./setup && rm .envA secret copied in, then deletedThe .env file stays in the COPY layer for good. Pass secrets with a BuildKit secret mount (RUN --mount=type=secret,...), which never writes them into a layer.
RUN apt-get update RUN apt-get install -y curlA stale package indexThe apt-get update layer is cached by its text and reused for months. A later install can then ask for package versions that are gone. Update and install in one RUN.
RUN curl -o big.tar ... RUN tar xf big.tar && rm big.tarCleaning up in a separate stepThe archive is already saved in the first layer, so the image does not shrink. Download, unpack and delete in the same RUN.
COPY . . # no .dockerignoreCopying more than you meantWithout a .dockerignore, changes in .git, node_modules or log files change the checksum and bust the cache. They also bloat the image.
RUN git clone https://...Commands that fetch the latestThe cache key is the command text, so a clone or a download of “latest” is never refreshed on its own. Pin a version, or rebuild with --no-cache when you mean to.

06 Check yourself

Question

With the deps-before-code Dockerfile, you add a new package to requirements.txt. Which steps rebuild?

Question

One step copies in a 500 MB file and the next step runs rm on it. How much bigger is the final image because of that file?

Question

You build RUN curl -o tool https://example.com/tool-latest today, and the file on the server is updated next week. What does next week’s build do, if nothing above that line changed?

07 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?