How would you optimize Docker layer caching in a Node.js Dockerfile to speed up repeated builds during development?
Short answer
Docker caches each instruction's resulting layer and reuses it on subsequent builds if that instruction and everything before it haven't changed -- ordering instructions from least-frequently-changing (installing dependencies) to most-frequently-changing (copying application…
Advertisement
AModel answer
Docker caches each instruction's resulting layer and reuses it on subsequent builds if that instruction and everything before it haven't changed -- ordering instructions from least-frequently-changing (installing dependencies) to most-frequently-changing (copying application source code) maximizes cache hits, since editing source code shouldn't force a slow 'npm ci' to rerun if package.json itself hasn't changed.
Example
# Good ordering: dependencies before source code COPY package*.json ./ RUN npm ci COPY . . # only this layer invalidates on a normal code change # Bad ordering: any code change invalidates the npm ci cache too COPY . . RUN npm ci
Real-world example
A team's Docker build time drops from over two minutes to under ten seconds for typical code-only changes after reordering their Dockerfile to copy package.json and run npm ci before copying the rest of the source code, letting Docker reuse the cached dependency-installation layer.
Likely follow-ups
- What specifically invalidates a Docker layer cache, causing that layer and everything after it to rebuild?
- How does BuildKit's cache mount feature further improve on this for the npm/yarn cache directory itself?
Related topics