Skip to the page

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.

The 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

  1. How does Docker's layer cache work?
  2. Why copy package.json before the rest of the code?
  3. Our image is 1.8 GB. How do you make it smaller?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview