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
- How do you secure Docker containers and images?
- What are multi-stage builds, and why use them?
- What is a container, and how does it differ from a virtual machine?
- What is the difference between an image and a container, and how do image layers work?
- What are Dockerfile best practices for production images?
- ARG or ENV: what is the difference, and how do you pass secrets into a build safely?
- CMD or ENTRYPOINT: what is the difference, and what are exec and shell forms?
- How do you make Docker images smaller?