Sphere
Log in Join
☆ 2

docker build recreates every layer after a one line change

I've been fighting our Dockerfile cache for two days. Any source change makes npm ci run again, so builds went from 40 seconds to six minutes. Dockerfile is the usual: FROM node:20-slim, WORKDIR /app, COPY . ., RUN npm ci --omit=dev, RUN npm run build. BuildKit is on. I know COPY . . before the install is the problem, but moving it below COPY package*.json ./ sounds too simple to be the whole story. There's also a .dockerignore that might be wrong. What am I missing?

⚑ Report

4 replies

☆ 0
C cache ·2026-10-01#1

You answered your own question. COPY . . invalidates everything after it whenever any tracked file changes, including your .git directory if it isn't ignored. Put COPY package.json package-lock.json ./ first, run npm ci off that layer, then COPY . . and build. Show us the .dockerignore, though. If it doesn't exclude node_modules you're copying the host's modules into the image and clobbering the installed ones.

⚑ Report
☆ 0
W works ·2026-10-05#2

Current .dockerignore is just node_modules and .git, nothing else. I moved the package files up like you said and the install layer is cached now, which is great. But the build layer still reruns on every change, which is expected I guess. The six minutes came mostly from npm ci downloading everything each time, so this already cut it to about a minute.

⚑ Report
☆ 0
S skill ·2026-10-15#3

One minute is normal for that Dockerfile. If you want the build layer cached too, look at docker build with BUILDKIT_INLINE_CACHE and CI cache mounts, but honestly for a six minute to one minute drop I'd stop there. Also add *.log and coverage to .dockerignore so a test run doesn't bust the cache.

⚑ Report
☆ 0
F fern ·2026-10-16#4

Also check whether your package-lock.json is actually stable. If something in the pipeline rewrites it on every run, a postinstall that touches it or different npm versions between dev and CI, the COPY package*.json layer changes every time and you lose the cache anyway. git diff -- package-lock.json after a build is a quick sanity check.

⚑ Report
Log in to reply.