🐳 Docker: Fix a Multi-Stage Build Caching a Stale npm Install Layer
The standard pattern of copying package.json before the rest of the source so npm install can be cached as its own layer only works if every file that actually determines what gets installed is part of that early COPY — and it’s an easy mistake to copy package.json alone while forgetting package-lock.json (or the equivalent yarn.lock / pnpm-lock.yaml), because Docker’s layer cache key is computed purely from the files that were actually copied into that step. The lock file can change — pinning entirely different transitive dependency versions — and the install layer’s cache key never moves, so Docker happily reuses an install from before the lock file update, indefinitely.
🔎 The Problem
FROM node:20 AS build WORKDIR /app COPY package.json ./ RUN npm install COPY . . RUN npm run build # package-lock.json changed (different transitive versions pinned), # but it was never part of the COPY above, so the cache key for # 'RUN npm install' is unchanged -> Docker reuses the OLD install layer
✅ Fix: Copy Every File the Install Actually Depends On
- Copy both
package.jsonAND its lock file (package-lock.json,yarn.lock, orpnpm-lock.yaml) before the install step — the cache key has to include every file that can change what gets installed, not just the one most people remember. - Prefer
npm ciovernpm installin the build stage; it fails loudly if the lock file andpackage.jsondisagree instead of silently resolving a slightly different tree, which also makes a stale-cache situation easier to notice. - When an install looks suspiciously fast for a dependency change you know should matter, rebuild with
--no-cacheonce to confirm whether you’re looking at a genuine result or a cache hit that shouldn’t have happened.
🚨 Why This Is Dangerous
- Shipping a production image built against dependency versions from weeks ago because the lock file update that was supposed to patch a vulnerable transitive package never actually got installed — the build looked fast and green the whole time, for exactly the wrong reason.
A cache key can only know about the files you showed it — a lock file you forgot to copy might as well not exist.
