Full lesson
Explore the full explanation, examples, and visuals at your own pace.
Dockerfile
You change one line in server.js, rebuild, and Docker reinstalls every npm package. That's slow. Look at this Dockerfile. The COPY dot dot instruction sits above RUN npm install. That ordering is the problem, even though package.json never changed. Let's see why Docker treats it that way.
FROM node:20
WORKDIR /app
COPY . .
RUN npm install
CMD ["node", "server.js"]Rebuild after editing server.js
Docker saves each step as a layer, a snapshot of the image, and the build cache reuses a snapshot when it can. Going down the rows, FROM and WORKDIR are cached, so they're instant. COPY misses, and then npm install rebuilds, taking about forty-two seconds, in this illustrative run.
A layer is reused only if unchanged:
Docker checks three things before reusing a layer: the instruction text, the input files, and the layer before it. COPY . . fails the file check because server.js changed. Then npm install fails the third check, since its parent layer is new.
- Its instruction text
- Its input files
- The layer before it
One miss cascades downward
FROM and WORKDIR are untouched, so they stay cached. But the server.js edit brings in a new input, and COPY . . becomes a miss. Now npm install has a brand new parent, so it rebuilds too, even though package.json never changed. One miss rebuilds everything after it.
Change a low block, rebuild above
Think of the image as a tower of blocks. node:20 and WORKDIR sit below the swap, so they stay put. But everything resting on COPY has to come off and be rebuilt. That puts slow npm install high in the tower, where one small edit knocks it loose.
Dockerfile, reordered
Here's the fix. We copy only package.json and package-lock.json first. The lockfile records the exact dependency versions. Then npm install runs, and only after that do we copy the rest of the code. Now npm install depends on dependencies alone, not on server.js.
FROM node:20
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm install
COPY . .
CMD ["node", "server.js"]Same edit, reordered build
Now make the same one-line edit to server.js and rebuild. FROM, WORKDIR, the package file copy, and npm install all come back cached, because package.json and the lockfile didn't change. Only the final COPY runs again, taking about 0.3 seconds in this illustration, instead of forty-two for the install.
One cache miss rebuilds every layer after it; put churn last.
One cache miss rebuilds every layer after it, so put the churn last. When you write a Dockerfile, order the instructions from what changes least to what changes most. Dependencies go first, your source code goes last, and a small edit stays a quick rebuild.
