Card 03/ 07

GotchaDifficulty: Advanced1 min

Cache Invalidation: One Source Edit Reinstalls Every Dependency

Why fixing a typo can cost ten seconds of package installs that did not change.

Cache invalidation is what happens when a layer, the stored result of one Dockerfile instruction, changes: that instruction and every one after it have to run again. With the instructions in the wrong order, a one-line change to your code throws away the cached dependency install, and every build pays for it again.

You fix a typo in one file, and the build spends ten seconds installing dependencies that did not change:

Dockerfiletext
FROM node:20-alpine
WORKDIR /app
COPY . .
RUN npm ci
CMD ["node", "server.js"]

COPY . . copies your whole project, so its layer changes whenever any file does. The cache is a chain: once a layer differs, every instruction after it runs again, whether or not that instruction cares about what changed.

RUN npm ci sits after the copy, so a one-character edit to a source file invalidates the install of every dependency. The install itself has not changed; it no longer has a cached layer underneath it to reuse.

It is easy to miss because every build still succeeds. It only gets slower, and the extra ten seconds are paid on every edit by everyone who builds the project.

The order is the bug, and nothing else here is wrong. The fix keeps the same instructions in a different order: copy the files that list the dependencies, install, and only then copy the rest of the source.