gotchaModeratepending
Gotcha: Docker COPY vs ADD and layer caching
Viewed 0 times
docker copylayer cachingmulti-stage builddockerignorebuild optimization
Error Messages
Problem
Docker builds are slow because layer caching is invalidated unnecessarily, or ADD is used instead of COPY.
Solution
Docker layer caching and COPY best practices:
Layer caching rules:
# RULE: COPY is preferred over ADD
# ADD has extra features you usually don't want:
# - Auto-extracts .tar files
# - Can fetch URLs
# Use COPY for simple file copying
# BAD: Invalidates cache on ANY source file change
FROM node:20-alpine
WORKDIR /app
COPY . . # Every file change busts cache
RUN npm install # Reinstalls ALL deps every time
RUN npm run build
# GOOD: Copy dependency files first, then source
FROM node:20-alpine
WORKDIR /app
COPY package.json package-lock.json ./ # Only deps change busts this
RUN npm ci # Cached if deps unchanged!
COPY . . # Source code changes
RUN npm run build
# GOOD: Multi-stage for smaller images
FROM node:20-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine AS production
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --production # Only production deps
COPY --from=build /app/dist ./dist
CMD ["node", "dist/index.js"]
# Use .dockerignore to avoid copying unnecessary files
# .dockerignore:
# node_modules
# .git
# .env
# *.md
# dist
# .vscodeLayer caching rules:
- Each instruction creates a layer
- If a layer changes, ALL subsequent layers are rebuilt
- Order: least-changing files first, most-changing last
- Use
--no-cacheto force full rebuild when needed
Why
Docker caches each layer. COPY invalidates cache when files change. By copying dependency manifests first, you only rebuild the expensive npm install step when dependencies actually change.
Context
Optimizing Docker builds
Revisions (0)
No revisions yet.