Card 04/ 07
All 7 cards
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
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
RUN npm ciThis layer now depends on the manifests alone, so it survives every edit that does not touch them.
Copy the source last
COPY . .The layer that changes most often is now the last one, so what it invalidates is only itself and what follows.
Measure it
$ time docker build -t my-api:1 . # after a one-line source edit
real 0m1.9sAgainst 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.