gotchadockerMajorpending
Gotcha: Docker build cache invalidation is order-dependent
Viewed 0 times
cachelayerinvalidationorderBuildKitcache-mount
Error Messages
Problem
Changing any file invalidates all subsequent layers, causing slow rebuilds even when only application code changed.
Solution
Order Dockerfile instructions from least to most frequently changed:
# BAD - any code change rebuilds node_modules:
COPY . .
RUN npm install
RUN npm run build
# GOOD - dependency install is cached unless package.json changes:
COPY package.json package-lock.json ./
RUN npm install
COPY . .
RUN npm run build
# BETTER - use multi-stage and cache mounts:
FROM node:20-alpine AS builder
WORKDIR /app
# Layer 1: System deps (rarely change)
RUN apk add --no-cache python3 make g++
# Layer 2: npm deps (change occasionally)
COPY package.json package-lock.json ./
RUN npm ci
# Layer 3: Source code (changes frequently)
COPY . .
RUN npm run build
# Cache mount (BuildKit):
RUN --mount=type=cache,target=/root/.npm npm ci
# Python equivalent:
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
# Check layer sizes:
docker history <image>
# Force rebuild without cache:
docker build --no-cache .
# BAD - any code change rebuilds node_modules:
COPY . .
RUN npm install
RUN npm run build
# GOOD - dependency install is cached unless package.json changes:
COPY package.json package-lock.json ./
RUN npm install
COPY . .
RUN npm run build
# BETTER - use multi-stage and cache mounts:
FROM node:20-alpine AS builder
WORKDIR /app
# Layer 1: System deps (rarely change)
RUN apk add --no-cache python3 make g++
# Layer 2: npm deps (change occasionally)
COPY package.json package-lock.json ./
RUN npm ci
# Layer 3: Source code (changes frequently)
COPY . .
RUN npm run build
# Cache mount (BuildKit):
RUN --mount=type=cache,target=/root/.npm npm ci
# Python equivalent:
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
# Check layer sizes:
docker history <image>
# Force rebuild without cache:
docker build --no-cache .
Why
Docker caches each layer. When a layer changes, all subsequent layers are invalidated. Ordering by change frequency maximizes cache hits.
Revisions (0)
No revisions yet.