‹ All Docker Interview Questions questions

Docker Interview Question 1: Build Cache Layer Order

Docker Interview Questions · Test 1 · question 1 of 10

Images & Build Cacheeasy

A Node.js service has this Dockerfile:

FROM node:20 / WORKDIR /app / COPY . . / RUN npm ci / CMD ["node", "server.js"]

Developers complain that changing a single line of application code makes docker build re-run npm ci and download every dependency again, even though package.json and package-lock.json did not change. Which change fixes this?

Select one answer
Show answer and explanation

Answer:

  • B. Copy package.json and package-lock.json first, run npm ci, then COPY . . for the rest of the source

Each Dockerfile instruction produces a layer, and when a layer's cache is invalidated, every layer after it must be rebuilt too. With COPY . . before RUN npm ci, any source edit changes the files copied by COPY, which invalidates that layer and forces npm ci to run again. Copying only the package manifests first, installing, and copying the frequently changing source last means a code edit invalidates only the final COPY layer; the dependency layer stays cached.

Option A is the opposite of the goal: --no-cache disables the cache entirely, so every build reinstalls dependencies.

Option C is a good practice (it keeps the host's node_modules out of the build context), but the order problem remains: COPY . . still changes on every source edit and still invalidates the npm ci layer after it.

Option D may make the image smaller, but the base image does not change the cache behaviour; the install still re-runs on every source change.

References: Optimize cache usage in builds; Docker build cache

Practice Test 1 ›

Study guides for Docker Interview Questions