The Analogy: Mise en Place on the Restaurant Line
A busy kitchen serving the same dishes hundreds of times a night cannot cook each order from raw ingredients start to finish; there is no time. The line runs on mise en place -- everything in its place, prepared before service begins. The long and expensive work is done once, up front: the stock simmers for eight hours, the sauce base is reduced, vegetables are blanched, proteins are portioned. When a ticket comes in, the cook assembles these ready components in seconds. The costly preparation is paid for once and reused across every plate that leaves the pass.
The order of that preparation is not arbitrary; it tracks what changes and what stays the same. The stock and the sauce base are stable -- identical for every dish, all week -- so they are made first and held. The volatile, per-order work, searing this particular steak and plating to this particular ticket, is done last, at the moment of service. A well-run line deliberately puts the stable, costly prep early and the fast, changing steps late, precisely so that a fresh ticket never forces anyone to re-simmer the stock.
This is exactly what a build cache is, and what a Dockerfile's instruction order controls. A Dockerfile is a sequence of steps, each producing a layer built on top of the one before it, and the cache lets an unchanged step be reused instead of re-run. Put the stable, expensive step -- installing dependencies -- early, and the volatile step -- copying your application source -- late, and then editing a source file reuses the cached dependency layer instead of reinstalling everything from scratch. You order the Dockerfile the way a kitchen orders its prep: costly and stable first, cheap and changing last.
But the cache reuses a prepared component only when nothing beneath it has changed, and the dependency runs strictly forward: change an early step and every step after it must be redone, because each was built on top of the one you altered. Re-reduce the stock and every sauce made from it is suspect and must be remade, however untouched it looks. The dangerous error is the cook who decides what to remake by glancing only at the written recipe card: the card for the sauce reads the same words as yesterday, so they ladle out yesterday's sauce, never noticing that the stock underneath it was remade this morning from a different set of bones. The recipe text is identical; the ingredient is not. That is precisely the mistake the build predictor at the end of this lesson makes when it declares a copy step cached because its instruction text is unchanged, blind to the fact that the files it copies are now different.
Syntax or Core Structure
A Dockerfile is read top to bottom, and each instruction produces one layer. The single most valuable habit is ordering those instructions by volatility: copy the dependency manifest and install dependencies before copying the source, so that a code change -- which happens dozens of times a day -- never invalidates the expensive install layer.
FROM node:20-slim
# deps first: stable and expensive, so it stays cached across source edits
COPY package.json package-lock.json ./
RUN npm ci
# source last: volatile, so only this layer and below rebuild on a code change
COPY src ./src
RUN npm run build
Why the order pays off is entirely mechanical. Docker keeps a layer's cached result and reuses it as long as that layer's cache key and every earlier layer's key are unchanged. The first changed layer forces a rebuild of itself and everything after it. Model that rule directly and edit a single source file:
def rebuild_from(old, new):
for i in range(len(new)):
if i >= len(old) or old[i][2] != new[i][2]:
return i
return None
def report(old, new):
first = rebuild_from(old, new)
total = 0
for i, (name, cost, key) in enumerate(new):
if first is not None and i >= first:
state = 'REBUILD'; total += cost
else:
state = 'cached'
print('%-18s %-8s %ds' % (name, state, cost))
print('rebuilt-time=%ds' % total)
return total
good_v1 = [
('FROM node:20', 1, 'from:node20'),
('COPY package.json', 1, 'copy:pkg:v1'),
('RUN npm install', 60, 'run:npm-install'),
('COPY src', 1, 'copy:src:v1'),
('RUN npm build', 10, 'run:npm-build'),
]
# edit a source file: only the COPY src content signature changes
good_v2 = [row[:] for row in good_v1]
good_v2[3] = ('COPY src', 1, 'copy:src:v2')
report(good_v1, good_v2)
Output:
FROM node:20 cached 1s
COPY package.json cached 1s
RUN npm install cached 60s
COPY src REBUILD 1s
RUN npm build REBUILD 10s
rebuilt-time=11s
The 60-second npm install stays cached because nothing before it changed. Only COPY src and the build step after it rebuild, for 11 seconds total. The dependency layer sits earlier in the file than the source layer, so a source edit never reaches back to it -- the stock is not re-simmered because someone changed the plating.
Technical Depth: Cache Keys and the Cost of Bad Ordering
What each instruction's cache key is actually made of
The cache is not keyed on the instruction text alone. Different instructions derive their key from different inputs, and knowing which is which is the whole game -- it is why re-ordering helps and why one particular class of change invalidates the cache invisibly.
| Instruction | Cache key derived from |
|---|---|
| FROM | the base image name and its resolved digest |
| RUN | the exact command string, verbatim |
| COPY and ADD | the checksum of the files being copied |
| ENV and ARG | the assigned value |
| WORKDIR and EXPOSE | the instruction text |
The row that surprises people is COPY and ADD. Their key is a checksum of the file contents, not the words COPY src ./src. Edit a source file without touching the Dockerfile and the COPY layer's key changes anyway, because the bytes it copies changed. That is correct and desirable -- it is how a code edit triggers a rebuild at all -- but it is also the exact behavior a naive tool forgets, as the next section shows.
Bad ordering re-runs the expensive layer
Put COPY . . before RUN npm install and you have moved the volatile step in front of the expensive one. Now any source edit changes the whole-context copy, and forward invalidation drags the install along with it. Compare the two orderings against the identical one-file source edit:
bad_v1 = [
('FROM node:20', 1, 'from:node20'),
('COPY . .', 1, 'copy:all:v1'),
('RUN npm install', 60, 'run:npm-install'),
('RUN npm build', 10, 'run:npm-build'),
]
bad_v2 = [row[:] for row in bad_v1]
bad_v2[1] = ('COPY . .', 1, 'copy:all:v2') # a source edit changes the whole-context copy
bf = rebuild_from(bad_v1, bad_v2)
bt = sum(c for _, c, _ in bad_v2[bf:])
bad_install = any(n == 'RUN npm install' for n, _, _ in bad_v2[bf:])
gf = rebuild_from(good_v1, good_v2)
gt = sum(c for _, c, _ in good_v2[gf:])
good_install = any(n == 'RUN npm install' for n, _, _ in good_v2[gf:])
print('bad-order: rebuilt=%d time=%ds install=%s' % (len(bad_v2) - bf, bt, 'rerun' if bad_install else 'cached'))
print('good-order: rebuilt=%d time=%ds install=%s' % (len(good_v2) - gf, gt, 'rerun' if good_install else 'cached'))
print('speedup=%.1fx' % (bt / gt))
Output:
bad-order: rebuilt=3 time=71s install=rerun
good-order: rebuilt=2 time=11s install=cached
speedup=6.5x
Same edit, same instructions, only the order differs. The bad ordering places COPY . . at index 1, so a source change invalidates it and everything after -- including the 60-second install -- for 71 seconds. The good ordering isolates the install behind the manifest copy, so it stays cached and the rebuild is 11 seconds. The 6.5x gap is not a micro-optimization; on a real image with a multi-minute dependency install it is the difference between a fast inner loop and one where every code change costs a coffee break.
Real World Example: A CI Build-Time Predictor
A CI system tries to be clever. Before running a build it predicts which layers will cache-hit, and if it predicts a full cache hit it routes the job to a fast lane and skips re-running the slow test suite, on the theory that nothing was rebuilt. The predictor decides a layer is cached by comparing each instruction's text to the last build. It looks reasonable, and it is quietly, dangerously wrong. Here it is beside a content-aware model of what Docker actually does, for the case that matters most -- a developer edits one source file and does not touch the Dockerfile:
def real_key(name, text, content_sig):
if name.startswith('COPY') or name.startswith('ADD'):
return text + '|' + content_sig # keyed on file content
return text
def flawed_key(name, text, content_sig):
return text # keyed on instruction text only
layers = [
('FROM node:20', 1, 'from:node20', 'x'),
('COPY package.json', 1, 'copy:pkg', 'pkgsig'),
('RUN npm install', 60, 'run:npm-install', 'x'),
('COPY src', 1, 'copy:src', 'srcsig'),
('RUN npm build', 10, 'run:npm-build', 'x'),
]
def build(keyfn, edited_src):
old, new = [], []
for name, cost, text, sig in layers:
s_new = sig + '2' if (name == 'COPY src' and edited_src) else sig
old.append((name, cost, keyfn(name, text, sig)))
new.append((name, cost, keyfn(name, text, s_new)))
f = rebuild_from(old, new)
t = sum(c for _, c, _ in new[f:]) if f is not None else 0
n = (len(new) - f) if f is not None else 0
return n, t
pn, pt = build(flawed_key, True)
rn, rt = build(real_key, True)
print('source file edited; Dockerfile text unchanged')
print('predictor: rebuilt=%d time=%ds' % (pn, pt))
print('reality: rebuilt=%d time=%ds' % (rn, rt))
print('miss=%d layers (%ds) the predictor called cached' % (rn - pn, rt - pt))
Output:
source file edited; Dockerfile text unchanged
predictor: rebuilt=0 time=0s
reality: rebuilt=2 time=11s
miss=2 layers (11s) the predictor called cached
The predictor reports a perfect cache hit -- zero layers rebuilt, an instant build -- because no instruction's text changed. The developer only edited a file. But Docker keys COPY src on the checksum of the files it copies, and those changed, so the real build rebuilds COPY src and the RUN npm build after it: two layers, eleven seconds, and a genuinely different image. The dashboard routes a real build into the instant lane and, because it believed nothing rebuilt, skips the tests on code that did change. It ships an untested image on the strength of a cache prediction that was looking at the recipe card while the ingredients changed underneath.
The fix is the difference between the two keyfn functions: for COPY and ADD, fold a content signature into the key so a file edit is visible. But even the corrected predictor has real limits worth stating plainly. It cannot see cache busting that originates outside the files: a moved node:20 tag resolves to a new base digest and invalidates FROM though nothing local changed, a build argument passed at build time changes an ARG layer's key, and a RUN apt-get install whose command string is fixed still pulls whatever the upstream repository serves that day -- the key says hit while the world moved. And the design flaw that persists even after the COPY fix is that this model treats each layer's key as purely local, when Docker's real key is cumulative: a layer's true key incorporates the keys of every parent above it, so two Dockerfiles sharing an identical RUN line do not share a cache entry unless everything above that line is also identical. A predictor that hashes instructions one at a time still cannot reason about the parent chain or cross-build cache sharing; the correct model threads a running parent hash through every layer, which is a materially different computation than a per-instruction lookup.
Common Mistakes
- Copying source before installing dependencies. Placing
COPY . .ahead ofRUN npm installmeans every code edit invalidates the copy and re-runs the install. Copy the manifest and lockfile, install, and only then copy the source.
- Assuming an unchanged Dockerfile means a cached build.
COPYandADDare keyed on the checksum of the files they copy, not on their instruction text. Editing a copied file busts the cache from that layer forward while the Dockerfile itself is untouched.
- Splitting
apt-get updateandinstallinto separate layers. Theupdatelayer caches and goes stale, so a later cachedinstallfetches against an old package index and can fail or install outdated versions. Combine them in a singleRUN.
- Building without a .dockerignore.
COPY . .with no ignore file pullsnode_modules,.git, and build output into the context. That churns the copy checksum on every build, busting the cache constantly and bloating the image.
- Pinning nothing with
FROM node:latest. The base image moves under you, so builds are not reproducible and theFROMlayer's digest changes silently. Pin a specific tag or, better, a digest.
- Shipping build tools in the final image. Without a multi-stage build, compilers and dev dependencies end up in the production image, enlarging it and widening the attack surface. Compile in a build stage and copy only the artifact into a slim runtime stage.
- Running as root. The default user is root, so a container escape lands as root on the shared host kernel. Add a non-root
USERin the final stage.
- Placing volatile instructions early. An
ADDof a URL or aCOPYof a frequently changing config near the top of the file invalidates everything below it on each change. Push volatile copies as late in the file as correctness allows.
- Expecting cache to help in CI without persisting it. CI runners are usually ephemeral, so unless you explicitly restore and save the layer cache or use a registry cache, every CI build starts cold and the ordering optimization saves nothing there.
Best Practices
- Order instructions by volatility: the base image and dependencies first, application source last, so the common case of a code edit never invalidates the expensive layers.
- Copy the dependency manifest and lockfile and install before copying the source, isolating the install behind a layer that changes only when dependencies actually change.
- Add a .dockerignore excluding
node_modules,.git, and build artifacts so the build context stays small and theCOPYchecksums stay stable.
- Pin the base image to a specific tag or digest so the
FROMlayer is reproducible and does not shift underneath your builds.
- Combine
apt-get updatewith itsinstallin oneRUNand clean the package lists in the same layer, so the index can never cache separately from the install.
- Use multi-stage builds: do the compiling in a build stage and copy only the finished artifact into a minimal runtime stage.
- Run the final stage as a non-root
USER, so a compromise inside the container does not begin with root on the shared kernel.
- In CI, persist the layer cache with a registry cache or the runner's cache store, so the volatility ordering actually pays off on cold runners.
Practice Exercises
- Extend the layer model with a build-argument layer whose key is the argument's value. Show that passing a new
--build-arginvalidates from that layer forward, and reason about where to place it to minimize rebuilds.
- Take the bad-order Dockerfile and rewrite it to good order, then run both models against a
package.jsonchange rather than a source change. Explain why this time both orderings must rebuild the install layer.
- Fix the flawed predictor so that
COPYandADDkeys include a content signature. Re-run the source-edit scenario and confirm the predictor's rebuilt count now matches reality.
- Model a multi-stage build as two layer lists, where the runtime stage copies one artifact out of the build stage. Show which stages rebuild when only a source file changes, and which stay cached.