Docker · Containers in practice
How do image layers and build caching work?
Short answer
Each instruction creates a content-addressed layer, and Docker reuses a cached layer when its parent and inputs are unchanged. Ordering instructions from least to most volatile maximises cache hits.
A layer is a filesystem diff plus metadata. Docker walks the Dockerfile in order and, for each instruction, checks whether a cached layer exists with the same parent and the same inputs. The first miss invalidates every later layer, because each layer depends on the one before it.
FROM node:20-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run buildWhat invalidates a cache entry
- A change to the instruction text itself
- A change to the files copied by COPY or ADD
- A changed ARG value referenced by the instruction
- A newer base image when the cache is refreshed
- By default, a RUN command is not re-executed if its layer is cached
Put dependency manifests before application source, combine related package installs into one RUN, and clean package caches in the same layer. BuildKit can also cache package manager downloads across builds with cache mounts, which is different from layer caching.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why does one changed COPY invalidate the rest of the build?
- 2How would you cache dependencies without copying the whole source tree?
- 3What is the difference between layer caching and a cache mount?
- 4When would you deliberately build with --no-cache?
Say it in the interview
Every instruction produces a layer, and Docker reuses a cached layer when the instruction, its parent and its inputs are unchanged. A miss invalidates all later layers, so I copy manifests and install dependencies before copying source. I also combine install and cleanup into one RUN, and I use BuildKit cache mounts for package downloads rather than relying only on layer caching.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Docker mock interview and get scored feedback on depth, clarity and confidence.