Layer caching and instruction order

Intermediate · 10 min

How BuildKit decides a step is cached: command text for RUN, file checksums for COPY, build args from first use. And why stale cache bites.

Before thisThe build context and .dockerignoreLayers, overlayfs and copy-on-write

Net Ninja · 10 min

Layer caching and instruction order

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Net NinjaReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Each step is cached by its parent plus its own inputs. The first step whose inputs changed misses, and every step that depends on it runs again.
  • A RUN step's cache key is its command text and environment, not what the command would fetch today, so RUN apt-get update stays stale until something above it changes.
  • COPY and ADD are keyed on a checksum of the copied files' contents and metadata. Modification time is ignored, so touching a file does not bust the cache.
  • A build argument changes the cache only where it is used. Every RUN after its ARG line sees it, so declare an ARG just before the step that needs it.
  • Order steps from least to most often changed: base image and system packages, then dependency manifests and install, then source code.
  • Force a rebuild with --no-cache, one stage with --no-cache-filter, a newer base image with --pull, and free space with docker builder prune.

Fast builds are cached builds

A build that takes six minutes is tolerable once. Run it forty times a day across a team and it is a tax on every change. Most of those six minutes repeat work: the same base image, the same npm ci, the same compile of code that did not change. The build cache exists to skip that, and instruction order decides how much of it you get.

The devops lesson gave the rule of thumb: copy the dependency manifest and install before copying source. This lesson is what the cache actually compares, which is what you need when the rule of thumb is not enough.

What a step’s cache key contains

BuildKit turns the Dockerfile into a graph of operations, and each operation’s cache key is built from its parent’s key plus its own inputs. The build cache invalidation page lists what the inputs are:

  • Base image. The FROM reference resolved to a digest. If the tag now points somewhere new and you build with --pull, everything misses.
  • RUN. The command string and its environment. The builder does not look at what the command would produce. RUN apt-get update is a hit forever, until something above it changes.
  • COPY and ADD. A checksum over the copied files’ contents and metadata, such as permissions. The page states that modification time is not part of it, so a git checkout that only touches timestamps still hits.
  • RUN --mount=type=bind. Checksummed like COPY.
  • Build arguments. Part of the key wherever they are used, which is less obvious than it sounds.

Once a step misses, every step that depends on it misses too. Steps in an unrelated stage are not affected, because the cache follows the graph, not the line numbers.

Watching an ARG move the cache

The Dockerfile reference says a build argument causes a miss “upon its first usage, not its definition”, and that every RUN after an ARG uses it implicitly, as an environment variable. I checked that against BuildKit’s own code. With BuildKit’s Dockerfile frontend, v0.35.1, as a Go library, I converted this Dockerfile to LLB, BuildKit’s build graph, twice, with two values of GIT_SHA, and printed each operation’s digest. The digest of an operation’s definition is the part of its cache key that comes from the Dockerfile:

FROM node:24-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
ARG GIT_SHA
COPY src/ ./src/
RUN echo "$GIT_SHA" > /app/REVISION
CMD ["node", "src/server.js"]
== GIT_SHA=a1b2c3
d0f376c12e29  Exec    [4/6] RUN npm ci --omit=dev
f4644620a042  File    [5/6] COPY src/ ./src/
1c58c149e4c0  Exec    [6/6] RUN echo "a1b2c3" > /app/REVISION
== GIT_SHA=d4e5f6
d0f376c12e29  Exec    [4/6] RUN npm ci --omit=dev
f4644620a042  File    [5/6] COPY src/ ./src/
5ae48511657c  Exec    [6/6] RUN echo "d4e5f6" > /app/REVISION

BuildKit names steps with the argument already expanded, which is why the value shows up in step 6. Only step 6 changed. The COPY on line 5 sits below the ARG but did not change, because only RUN steps receive build arguments as environment. npm ci sits above the ARG, so a new commit SHA cannot touch it. Move ARG GIT_SHA to the top of the file and npm ci would be in its scope, and every commit would reinstall every dependency. What this experiment cannot show is the file checksums for COPY, which BuildKit computes at build time from the context. That needs a real build.

Stale cache is a correctness problem

The cache does not know that the world changed. Two patterns that follow from “keyed on the command text”:

# Bad: update is cached separately and goes stale
RUN apt-get update
RUN apt-get install -y curl

# Good: always refresh the index in the same step that installs
RUN apt-get update && apt-get install -y --no-install-recommends curl \
 && rm -rf /var/lib/apt/lists/*

When you add a package to the second line of the bad version, the update step still hits, and apt-get tries to download versions from an index that may be months old. Combining the two means any change to the install list refreshes the index too.

For security updates, a cached layer is only as fresh as the last time it missed. Scheduled CI builds usually pass --pull and sometimes --no-cache for that reason, a trade covered in build caches in CI.

Ordering for hits

A working order for most services:

  1. FROM, then system packages that rarely change.
  2. The dependency manifest only: package.json and the lockfile, requirements.txt, go.mod and go.sum.
  3. The dependency install.
  4. ARGs that change often, declared right before their use.
  5. The source code, then the build.

Keep the context lean too. A file excluded by .dockerignore cannot bust COPY . ., so a log file or a local .env changing on your machine stops costing you a rebuild.

Controlling the cache

docker build --no-cache .                 # ignore the cache for every step
docker build --no-cache-filter test .     # only for the stage named test
docker build --pull .                     # re-resolve FROM tags to their newest digest
docker builder prune                      # delete build cache to free disk

The cache lives in the builder, not in the image. A new CI runner starts empty, which is the problem build caches in CI solves.

About the video

The embed is Net Ninja’s “Docker Crash Course #8 - Layer Caching”, February 2022, 10 minutes. Its chapters cover layers, building the image, how layer caching works, reordering the Dockerfile so npm install is cached, and the faster rebuild workflow. It is a beginner demo with a Node app, and it predates the newer BuildKit flags such as --no-cache-filter, which the lesson adds. YouTube reports an English original audio track. Benjamin Porter’s video in deeper rewrites a naive Dockerfile the same way.

What was run: the two LLB dumps above are real output from a Go program calling dockerfile2llb.Dockerfile2LLB from BuildKit v0.35.1, with the node:24-slim reference resolved against Docker Hub. Nothing was executed and no files were checksummed. The cache rules are from the build cache invalidation page and the Dockerfile reference, checked 2026-11-28.

Where this fits

Ordering keeps rebuilds fast. Next, keeping the final image small by building in one stage and shipping from another: multi-stage builds.

Check yourself

  1. 01Your Dockerfile has RUN apt-get update on one line and RUN apt-get install -y curl on the next. Months later you add a package to the install line and the build fails with 404s. Why?

    The update step's text did not change, so its cached layer from months ago was reused, with an old package index pointing at versions the mirror no longer has. Combine update and install in one RUN so they always run together.

  2. 02You touch every file in the repository without editing any. Does COPY . . miss the cache?

    No. The cache checksum for COPY uses file contents and metadata but ignores modification time, so unchanged contents still hit.

  3. 03ARG GIT_SHA is declared near the top, before RUN npm ci. Every commit reinstalls all dependencies. Why, and what is the fix?

    A RUN after an ARG gets the argument in its environment, so a new GIT_SHA changes the npm ci step's cache key. Move the ARG down to just before the step that actually uses it.

  4. 04How do you rebuild only the test stage from scratch while keeping the cache for everything else?

    docker build --no-cache-filter test . invalidates the cache for that stage only. --no-cache would rebuild every step.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark