Node.js › Docker & Deployment
How would you optimize Docker layer caching in a Node.js Dockerfile to speed up repeated builds during development?
AdvancedAnswer
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.
# 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 ciReal-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.