Lesson 12 of 24Building images well
Image Layers and the Build Cache
What a layer really is on disk and in a registry, the exact rules BuildKit uses to reuse one, and how to find the bytes that make an image fat.
You can now ship a full stack in small production images. This unit goes under the hood of the build itself, and it goes deeper than the lessons so far; come back to it after you have shipped a few images if it feels heavy. A teammate adds ARG GIT_SHA near the top of the Dockerfile so the image can report its version, and the next morning every CI build takes nine minutes instead of ninety seconds. Another teammate "cleans up" an image by adding RUN rm -rf /root/.cache at the end, and the image stays exactly the same size. Both bugs come from the same gap: knowing that layers are cached, but not knowing what a layer is or what the cache key is made of. In Writing a Dockerfile you learned to put dependencies before source. This lesson goes underneath that rule, so you can debug a slow or bloated build from first principles instead of by trial and error.
What a layer actually is
A layer is a tar archive of filesystem changes: the files a step added or changed, plus markers for files it deleted. That is all. There is no "diff of bytes inside a file". If a step changes one line of a 50 MB file, the layer contains the whole new 50 MB file.
An image ties layers together with two small JSON documents:
- The config lists the layers in order (as
rootfs.diff_ids) and holds the metadata:Env,Cmd,Entrypoint,User,WorkingDir, labels, the target platform, and ahistoryentry per instruction. The image ID is the sha256 of this config. - The manifest points at the config and at each layer blob, by digest. When you pull by digest (
python@sha256:...), you are naming a manifest.
Two different hashes describe the same layer, and mixing them up confuses people in interviews:
| Hash | Hash of | Where you see it |
|---|---|---|
| diff ID | the uncompressed tar | docker image inspect under RootFS.Layers |
| blob digest | the compressed tar that travels over the network | the manifest, registry UIs, docker pull progress lines |
Because both are content hashes, identical layers are stored once. Ten services built FROM python:3.13-slim share one copy of the base layers on disk, and a push uploads only blobs the registry does not already have.
A tag is just a pointer. Pushing a new build with the same tag moves the pointer; nothing else changes.
You can see the diff IDs of any local image:
docker image inspect --format '{{json .RootFS.Layers}}' python:3.13-slimDeletes are whiteouts, and on disk it is all overlay
You saw a model of a union filesystem in Images and Containers. In the real tar format, a delete is a marker file: removing /app/secret.txt adds an empty entry called /app/.wh.secret.txt, and replacing a whole directory adds .wh..wh..opq inside it (an "opaque" directory). The original bytes are still sitting in the older layer.
On a Linux host, the classic overlay2 storage driver unpacks each layer into its own directory and mounts them with the kernel's OverlayFS: the image layers become read-only lowerdir entries, the container gets a writable upperdir, and the process sees the combined merged view. Docker Engine 29 and later use the containerd image store by default on fresh installs, which does the same job through containerd "snapshotters" (overlayfs by default). One visible difference: containerd keeps both the compressed blobs and the unpacked layers, so the same images use more disk than they did under overlay2. If you upgraded an older engine, check the docs for which store you are on.
Which instructions make layers
Only three instructions add filesystem content. The rest edit the config.
| Instruction | Adds a filesystem layer? | Notes |
|---|---|---|
RUN | Yes | Whatever the command changed on disk |
COPY, ADD | Yes | The copied files, with their mode and ownership |
WORKDIR | Only if the directory is new | Creates the directory; otherwise config only |
ENV, ARG, LABEL, USER, EXPOSE, CMD, ENTRYPOINT, HEALTHCHECK | No | Config metadata. They show up in docker history as 0B rows |
docker history lists one row per instruction, with the size each one added. Add --no-trunc to see the full command, which is how you find the step that made the image fat:
docker history --no-trunc myapi:1.4Match each instruction to what it changes.
The exact cache rules
BuildKit (the default builder since Docker Engine 23) decides whether to reuse a step by computing a cache key from the step's inputs. If a key matches something in the builder's cache, the step is skipped. The inputs differ by instruction, and the differences are where the bugs live.
RUN is keyed on its command string, plus the parent step and the environment it runs with. BuildKit never looks at what the command would fetch. So RUN apt-get update is cached forever with whatever index existed on the day it first ran, and so is RUN pip install requests with no version pin, and so is RUN curl -fsSL https://example.com/install.sh | sh. The build is fast and quietly stale. The fix is to make the inputs explicit (a lockfile copied in before the step, a pinned version in the command), not to sprinkle --no-cache.
COPY and ADD are keyed on a checksum of the copied files. The checksum covers file contents and metadata such as permissions, but not the modification time. A fresh git clone in CI gives every file a new mtime and still hits the cache. A chmod +x on a script does change the key.
ARG busts the cache at first use, not at its definition. The detail that catches teams: every RUN after an ARG line receives that argument as an environment variable, whether or not the command mentions it. So with ARG GIT_SHA at the top of a stage, every new commit changes the input of every later RUN, including the slow dependency install. Built-in proxy args like HTTP_PROXY are the exception; they are left out of the cache key unless you declare them.
Secrets are not part of the key. Changing the value of a build secret does not rebuild the step that mounts it. If you rotate a token and need a rebuild, change a build arg too, or use --no-cache-filter.
One miss poisons the rest of the stage. Each key includes the parent's key, so once a step misses, every step after it misses as well. Stages that do not depend on the changed stage are unaffected, which is one reason multi-stage builds cache well.
The setup: ARG GIT_SHA is declared right after FROM, and CI passes --build-arg GIT_SHA=<commit> on every build.
Here is a model of those rules. It keys RUN on the command plus every declared ARG, keys COPY on file contents and mode but not mtime, and treats ARG and LABEL as metadata. Run it, then try moving other lines around.
Press Run (⌘ Enter) to see what happens.ARG BUILD_DATE right after FROM, and CI passes the current time. The only later use is LABEL build-date=$BUILD_DATE on the last line. What happens to the cache?Reading the build output
When a build is slow, do not guess. Run it with plain progress output and read which steps were cached:
docker build --progress=plain -t myapi:dev .Each step prints a numbered block. Reused steps say CACHED; the first step that does real work is your culprit, and everything below it is collateral. A typical slow build looks like this:
#6 [2/6] COPY pyproject.toml uv.lock ./
#6 CACHED
#7 [3/6] RUN uv sync --locked --no-install-project
#7 0.412 Resolved 41 packages in 2ms
#7 38.90 Installed 41 packages in 1.21s
#7 DONE 39.6sStep 2 hit and step 3 missed, so the input that changed belongs to step 3: its command string, its environment (look for an ARG or ENV above it), or its parent. If the miss is at a COPY, the copied files changed, which usually means the source path is too broad (COPY . .) or .dockerignore lets churn in, such as .git, test reports or a local .venv.
Two flags help while you investigate: --no-cache forces a full rebuild, and --no-cache-filter <stage> rebuilds only the named stage. Check the docs for the exact stage name rules.
Finding the bytes that make an image fat
Layers only ever add. A RUN rm in a later layer writes whiteouts that hide files; the bytes still ship in the earlier layer and still count toward pull time and storage. These two Dockerfiles produce very different images:
FROM python:3.13-slim
RUN apt-get update && apt-get install -y build-essential
COPY . /src
RUN pip install /src
RUN apt-get purge -y build-essential && rm -rf /var/lib/apt/lists/*FROM python:3.13-slim AS build
RUN apt-get update && apt-get install -y --no-install-recommends build-essential \
&& rm -rf /var/lib/apt/lists/*
COPY . /src
RUN python -m venv /venv && /venv/bin/pip install --no-cache-dir /src
FROM python:3.13-slim
COPY --from=build /venv /venv
ENV PATH="/venv/bin:$PATH"In the bad version, the compiler toolchain lives in layer two forever, and the purge only adds a layer of whiteouts. In the good version, the compiler only exists in the build stage, and the final stage receives one finished virtualenv. Cleanup has to happen in the same RUN that created the files, or the files must never reach the final stage at all. The same trap catches people the other way round: COPY a folder in, then RUN rm -rf it, and the bytes are still in the COPY layer.
What does this print?
layers = [
("RUN apt-get install build-essential", 310),
("COPY . .", 2),
("RUN make", 40),
("RUN apt-get purge -y build-essential && rm -rf /var/lib/apt/lists/*", 0),
]
size = 0
for cmd, mb in layers:
size += mb
print(size, "MB")
print(max(layers, key=lambda l: l[1])[0])For a closer look, the open source tool dive opens an image layer by layer, shows the files each layer added, and estimates "wasted space": files that were overwritten or deleted by a later layer. That number is the bytes you are shipping for nothing.
dive myapi:1.4Reproducible builds
Build the same Dockerfile twice from the same commit and you usually get two different image digests. Nothing is broken; the inputs changed in ways the cache key does not see:
- Timestamps. Each config records a
createdtime, and files written byRUNget the current time, so the layer tars differ byte for byte. - Moving upstream.
apt-get install curlon Monday and on Friday may install different patch versions.FROM python:3.13-slimfollows a tag that is rebuilt for security fixes. - Unpinned dependencies. Anything resolved at build time without a lockfile.
Why care? Identical inputs giving an identical digest lets you prove a published image came from a given commit, lets two CI systems check each other, and avoids pushing a "new" image that contains nothing new. The levers:
- Pin the base image by digest (
FROM python:3.13-slim@sha256:...) and let Renovate or Dependabot bump it. - Install from lockfiles (
uv sync --locked,npm ci) and pin OS packages where it matters. - Set
SOURCE_DATE_EPOCH(as an environment variable or build arg), a standard variable that BuildKit uses for the timestamps in the image config and history. To also rewrite the timestamps of files inside layers, the image exporter has arewrite-timestamp=trueoption. A common choice is the timestamp of the commit being built. Check the docs for the version requirements.
Full bit-for-bit reproducibility is hard (OS package mirrors change underneath you). Most teams settle for "same lockfiles and same base digest give the same software", which is the part that matters for debugging and security.
Putting it together: a debugging order
CI builds suddenly got slow. Put these investigation steps in a sensible order.
- Tap the steps below in the right order.
git clone on every run, so every file has a new modification time. The Dockerfile copies uv.lock before the install step. Does the install step hit the cache (assuming the cache itself is available on the runner)?- layer
- A tar archive of filesystem changes from one
RUN,COPYorADD, stored and shared by its content hash. - diff ID
- The sha256 of a layer's uncompressed tar, listed in the image config. The registry uses the compressed blob digest instead.
- image config
- JSON holding metadata (env, command, user) and the ordered layer list. The image ID is its hash.
- whiteout
- A
.wh.marker in a layer that hides a file from lower layers without removing its bytes. - cache key
- The hash BuildKit computes from a step's command, environment, parent and copied file checksums. A match means the step is skipped.
- SOURCE_DATE_EPOCH
- A standard variable that fixes the timestamps written into an image so identical inputs can give an identical digest.