Solved

Docker reinstalls every dependency when I change one line of code

Asked by Leilani Kahale · 549 views · 3 replies

Leilani Kahale5 messages

Every tiny code change means waiting three minutes for npm ci again. My Dockerfile:

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

3 replies

Tomasz WiśniewskiSolution

Docker caches each step and reuses it until something that step depends on changes. COPY . . depends on every file in your project, so any edit invalidates it, and every step after it reruns, including the install.

Copy the dependency manifests on their own first, install, and only then copy the code:

FROM node:22-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
CMD ["node", "server.js"]

Now the install only reruns when the lockfile changes. Also add a .dockerignore containing at least node_modules and .git. Otherwise you copy your local node_modules over the freshly installed one, and the build context is huge too.

Link
Kenji Morita

And for when the lockfile does change: a BuildKit cache mount keeps npm's download cache between builds, so only new packages get downloaded:

RUN --mount=type=cache,target=/root/.npm npm ci
Link
Leilani Kahale

Rebuilds after a code change went from three minutes to about four seconds. I would never have guessed the order of two lines mattered that much.

Link