Interview Q&A / Docker & Kubernetes

IntermediateQuick answer1 min readUpdated 3 Oct 2026

Why do Node.js Dockerfiles use npm ci and copy package.json before the source code?

SHORT ANSWER

Copying package.json first lets Docker cache the dependency layer, so npm only reinstalls when dependencies change. npm ci installs exactly what package-lock.json lists, giving reproducible builds.

Explain it simply

Think of cooking: you buy ingredients (dependencies) once and reuse them, but you change the seasoning (your code) every time. If the shopping were redone for every seasoning change, it would be wasteful.

Docker caches layers and reuses one only if its instruction and inputs are unchanged. If you COPY . . first and then RUN npm install, any code edit invalidates the cache and reinstalls every package. By copying package*.json first, running the install, and only then copying the rest, the install layer is reused until the dependency files change. Code edits then rebuild in seconds.

npm ci deletes node_modules, installs exactly the versions in package-lock.json and fails if the lock and package.json disagree, so builds are repeatable. Add --omit=dev for production images. The same pattern applies to requirements.txt in Python and pom.xml in Maven.

Example

dockerfile
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev      # cached until package files change
COPY . .
CMD ["node", "server.js"]

What to say in the interview

"I copy package.json and the lock file first, run npm ci, then copy the source, so the dependency layer is cached across code edits. npm ci also installs exactly what the lock file says for reproducibility."

Common mistakes

  • Using COPY . . before installing dependencies and losing the cache on every edit.

#dockerfile#layer-caching#nodejs

Related questions

Practise more Docker & Kubernetes questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Docker & Kubernetes quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.