How to optimize Docker layer caching?
· Category: Docker
Short answer
Optimize Docker layer caching by ordering Dockerfile instructions from least to most frequently changing, using multi-stage builds, and leveraging BuildKit cache mounts for dependency managers.
Steps
- Place
COPYfor dependencies beforeCOPYfor application code. - Use
RUN --mount=type=cachefor package manager caches. - Combine related commands into a single
RUNlayer. - Use
.dockerignoreto prevent unnecessary cache invalidation.
Example
# syntax=docker/dockerfile:1
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
RUN npm run build
CMD ["node", "dist/server.js"]
Tips
- Use
docker build --no-cachesparingly; rely on cache for speed. - Pin base image versions to avoid unexpected cache invalidation.
- Use
docker buildxfor advanced caching and remote cache exports.
Common issues
COPY . .invalidates the cache on any file change; be selective.- Secrets or build args that change frequently should be used late in the Dockerfile.
- Without BuildKit, cache mounts are unavailable.