Optimize Dockerfile layer caching for npm install
layer caching mechanics.
copying all source first invalidates the npm install layer on any code change; instead copy package.json and lockfile, run npm install, then copy the rest.
WHAT THIS TESTS It checks whether you understand how the build cache keys on instructions and file content, and can reorder a Dockerfile to keep expensive steps cached.
A GOOD ANSWER COVERS Docker builds images as a stack of layers, one per instruction. A layer is reused from cache only if the instruction and its inputs are unchanged; once a layer is invalidated, every subsequent layer rebuilds too. Copying the entire source tree before npm install ties the install layer to all source files, so editing any line of application code invalidates the COPY layer and forces npm install to run from scratch, even though dependencies did not change. The fix is to copy only package.json and package-lock.json first, run npm install (or npm ci), and only then COPY the rest of the source. Now dependency installation stays cached across source-only edits.
COMMON WRONG ANSWERS Thinking the whole image rebuilds regardless of order, so ordering does not matter. Forgetting to copy the lockfile, which hurts reproducibility. Not knowing invalidation cascades downward from the first changed step.
LIKELY FOLLOW-UPS How does the cache key get computed for COPY? What is npm ci versus npm install here? How do BuildKit cache mounts further speed this up?
ONE CONCRETE EXAMPLE Restructured: COPY package*.json ./ then RUN npm ci then COPY . . On a routine code change only the final COPY and later steps rerun; npm ci is served from cache, cutting a multi-minute install to seconds. Editing package.json correctly busts the install layer so dependencies refresh.
Read the original → docs.docker.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.