Docker interview question · Most asked

How does Docker build caching work, and how do you order a Dockerfile to use it well?

Summary

Each instruction's result is cached; on rebuild, Docker reuses cached layers until it reaches an instruction whose inputs changed (the instruction text, or for COPY/ADD the checksums of copied files), and every instruction after that is rebuilt. So put rarely changing steps first and frequently changing ones (copying source code) last.

Longer Answer

Classic pattern: copy only the dependency manifests, install dependencies, then copy the rest of the source. Code edits then reuse the cached dependency layer.

FROM node:22-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY . .
CMD ["node", "server.js"]

BuildKit adds cache mounts (RUN --mount=type=cache,target=/root/.npm npm ci) that keep package-manager caches between builds, and remote cache export/import (--cache-to, --cache-from) so CI runners share caches. A .dockerignore keeps irrelevant files (.git, node_modules, logs) from invalidating COPY . ..

Key Points

  • Cache reused until the first changed instruction.
  • Dependencies before source code.
  • .dockerignore to avoid needless invalidation.
  • BuildKit cache mounts and remote caches.

More most-asked Docker questions

← All Docker questions