Skip to content

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.

17 min read0/5 questions

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 a history entry 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:

HashHash ofWhere you see it
diff IDthe uncompressed tardocker image inspect under RootFS.Layers
blob digestthe compressed tar that travels over the networkthe 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.

How an image is put together
myapi:1.4: a movable namemyapi:1.4a movable nameManifest: sha256:9f2c...Manifestsha256:9f2c...Config: Env, Cmd, diff_idsConfigEnv, Cmd, diff_idsBase layers: shared, about 45 MBBase layersshared, about 45 MBDeps layer: about 30 MBDeps layerabout 30 MBCode layer: about 40 KBCode layerabout 40 KBpoints at

A tag is just a pointer. Pushing a new build with the same tag moves the pointer; nothing else changes.

1/4

You can see the diff IDs of any local image:

docker image inspect --format '{{json .RootFS.Layers}}' python:3.13-slim

Deletes 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.

InstructionAdds a filesystem layer?Notes
RUNYesWhatever the command changed on disk
COPY, ADDYesThe copied files, with their mode and ownership
WORKDIROnly if the directory is newCreates the directory; otherwise config only
ENV, ARG, LABEL, USER, EXPOSE, CMD, ENTRYPOINT, HEALTHCHECKNoConfig 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.4
Match the pairs0/5 matched

Match each instruction to what it changes.

Choose an item, then its match on the other side.

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.

ARG GIT_SHA at the top of the stage
  1. LABEL org.opencontainers.image.revision=$GIT_SHAconfig only
  2. RUN uv sync --lockedinstalls your project, 3 s
  3. COPY app/ ./app/
  4. RUN uv sync --locked --no-install-projectdependencies, 45 s
  5. COPY pyproject.toml uv.lock ./
  6. ARG GIT_SHAdeclared early
  7. FROM python:3.13-slim

The setup: ARG GIT_SHA is declared right after FROM, and CI passes --build-arg GIT_SHA=<commit> on every build.

1/4

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.

Pythoncache_rules.py
import hashlib def digest(*parts: str) -> str: return hashlib.sha256("\0".join(parts).encode()).hexdigest()[:10] def build(dockerfile: list[str], files: dict, build_args: dict, cache: dict) -> None: parent = "" # cache key of the step below args: dict[str, str] = {} total = 0 for line in dockerfile: op, _, rest = line.partition(" ") if op == "ARG": name, _, default = rest.partition("=") args[name] = build_args.get(name, default) print(f" meta {line}") continue if op in ("LABEL", "CMD", "EXPOSE"): print(f" meta {line}") # image config only, no layer continue parts = [parent, line] if op == "RUN": # every RUN sees all declared ARGs as env vars parts += [f"{k}={v}" for k, v in sorted(args.items())] if op == "COPY": src = rest.split()[0] for path in sorted(files): if src == "." or path == src or path.startswith(src): f = files[path] parts.append(f"{path}:{f['data']}:{f['mode']}") # no mtime key = digest(*parts) seconds = int(line.split("#")[1]) if "#" in line else 1 if key in cache: print(f" CACHED {line.split('#')[0].strip()}") else: print(f" BUILD {line.split('#')[0].strip()} ({seconds}s)") total += seconds cache[key] = True parent = key print(f" -> {total}s of work\n") dockerfile = [ "FROM python:3.13-slim", "ARG GIT_SHA=dev", "COPY pyproject.toml uv.lock ./", "RUN uv sync --locked --no-install-project #45", "COPY app/ ./app/", "RUN uv sync --locked #3", "LABEL org.opencontainers.image.revision=$GIT_SHA",]files = { "pyproject.toml": {"data": "fastapi", "mode": "644", "mtime": 1}, "uv.lock": {"data": "fastapi==0.120", "mode": "644", "mtime": 1}, "app/main.py": {"data": "v1", "mode": "644", "mtime": 1},}cache: dict = {} print("1) first build")build(dockerfile, files, {"GIT_SHA": "a1b2c3"}, cache) print("2) git checkout touches main.py (new mtime, same bytes)")files["app/main.py"]["mtime"] = 2build(dockerfile, files, {"GIT_SHA": "a1b2c3"}, cache) print("3) new commit, docs only: GIT_SHA changes")build(dockerfile, files, {"GIT_SHA": "d4e5f6"}, cache) print("4) ARG moved to the end: one build to prime, then a new commit")late = [l for l in dockerfile if not l.startswith("ARG")]late.insert(-1, "ARG GIT_SHA=dev")build(late, files, {"GIT_SHA": "a1b2c3"}, cache)build(late, files, {"GIT_SHA": "0ff1ce"}, cache)
Output
Press Run (⌘ Enter) to see what happens.
Quick check
A Dockerfile declares 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?
Need a nudge? A hint rules out a wrong answer.

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.6s

Step 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:

Dockerfile.bad
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/*
Dockerfile.good
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.

Predict the outputPython

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])
Need a nudge? Hints walk you through it.

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.4

Reproducible 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 created time, and files written by RUN get the current time, so the layer tars differ byte for byte.
  • Moving upstream. apt-get install curl on Monday and on Friday may install different patch versions. FROM python:3.13-slim follows 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 a rewrite-timestamp=true option. 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

Put it in order5 steps

CI builds suddenly got slow. Put these investigation steps in a sensible order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
Your CI does a fresh 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)?
Need a nudge? A hint rules out a wrong answer.
Key terms
layer
A tar archive of filesystem changes from one RUN, COPY or ADD, 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.