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

  1. Place COPY for dependencies before COPY for application code.
  2. Use RUN --mount=type=cache for package manager caches.
  3. Combine related commands into a single RUN layer.
  4. Use .dockerignore to 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-cache sparingly; rely on cache for speed.
  • Pin base image versions to avoid unexpected cache invalidation.
  • Use docker buildx for 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.