Card 04/ 07

WalkthroughDifficulty: Advanced1 min

Ordering a Dockerfile So the Cache Survives

The fix is to put the thing that rarely changes above the thing that changes constantly.

Reordering so a source edit stops reinstalling dependencies

Step 1 of 4

Copy only what the install needs

text
COPY package.json package-lock.json ./

These two files change when a dependency changes, and not when you edit a function.

Install, while nothing else has been copied

text
RUN npm ci

This layer now depends on the manifests alone, so it survives every edit that does not touch them.

Copy the source last

text
COPY . .

The layer that changes most often is now the last one, so what it invalidates is only itself and what follows.

Measure it

bash
$ time docker build -t my-api:1 .   # after a one-line source edit
real	0m1.9s

Against roughly twelve seconds for the same edit in the other order.

The rule generalises past Node: copy the dependency manifest, install, then copy the source. Every ecosystem has the same two files.