Containers, Dockerfiles and layers · mid
Layers and the build cache
Each filesystem-changing instruction creates a layer, and Docker reuses a cached layer until that instruction or the files it copies change, after which every later step rebuilds, so you copy package files and install dependencies before copying the rest of the code.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- RUN, COPY and ADD create layers; layers are cached by the instruction text and the checksum of copied files.
- Once one step's cache is invalid, all following steps rebuild. Order steps from least to most frequently changing: base image, system packages, package*.json + npm ci, then source code, then the build.
- COPY package.json package-lock.json ./ then RUN npm ci, then COPY . . : editing source code no longer reinstalls dependencies.
- BuildKit (the default builder) supports cache mounts: RUN --mount=type=cache,target=/root/.npm npm ci keeps the npm cache between builds without putting it in the image.
- Deleting files in a later layer does not shrink the image (they still exist in the earlier layer). Clean up in the same RUN, or use multi-stage builds.
- Inspect with docker history <image> and docker image ls; smaller images pull and start faster.
The red pen
Common traps: mistake → fix
Mistake: COPY . . first is fine because Docker caches everything
Fix: any code change invalidates that layer and forces npm ci to run again.
Mistake: RUN rm -rf /tmp/big in a new layer makes the image smaller
Fix: the files remain in the earlier layer.
Easy to hard
Questions interviewers ask, easy to hard
- How does Docker's layer cache work?
- Why copy package.json before the rest of the code?
- Our image is 1.8 GB. How do you make it smaller?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.