debugModeratepending
Docker build cache not working -- layer invalidation
Viewed 0 times
Docker cachelayer invalidationCOPY ordermulti-stage.dockerignore
dockerterminal
Error Messages
Problem
Docker build is slow because it rebuilds layers that should be cached. Adding one line of code triggers npm install to run again. Build takes minutes instead of seconds.
Solution
Docker caches each layer and invalidates everything below a changed layer. Optimize by: (1) Copy package.json BEFORE source code: COPY package*.json ./ then RUN npm ci, then COPY . . Source changes do not invalidate the npm install layer. (2) Use multi-stage builds to separate build deps from runtime. (3) Use .dockerignore to exclude node_modules, .git, etc. (4) Order Dockerfile instructions from least to most frequently changing.
Why
Docker builds layers top-down. If layer N changes, all layers after N are rebuilt. Copying all source files before npm install means any code change invalidates the install layer.
Code Snippets
Optimized Dockerfile layer caching
# WRONG: any source change rebuilds npm install
COPY . .
RUN npm ci
# RIGHT: separate dependency install from source
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
# Multi-stage: smaller final image
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
CMD ["node", "dist/index.js"]Revisions (0)
No revisions yet.