I fixed a typo in a README. One character. Then I ran docker build and watched it reinstall every package in my package-lock.json from scratch, which took about a minute and a half.
I hadn't touched package.json and I hadn't touched the lockfile. Docker re-ran npm ci on every build anyway, and for a few weeks I assumed that was just how Docker worked.
It isn't. My build context had two things in it that never belonged there, and one of them changes every time you look at it.
TL;DR
- Docker re-runs
npm cievery build when any file copied before that step changes. WithCOPY . .aboveRUN npm ci, that means every file in the repo. - Without a
.dockerignore, your.gitfolder is part of the build context..git/indexcan be rewritten by a plaingit status, so the cache can break even when you haven't made a commit. - In
.dockerignore,node_modulesonly matches the folder at the context root. Nested folders in a monorepo need**/node_modules. - Fix: copy only
package.jsonandpackage-lock.json, runnpm ci, thenCOPY . .. Add a.dockerignorethat excludes.git,**/node_modules, build output, and.envfiles.
Why does Docker re-run npm ci every build?
Docker re-runs npm ci every build because the layer cache is a chain. When one step's cache key changes, every step after it rebuilds too. If COPY . . sits above RUN npm ci, any changed byte anywhere in the build context invalidates the copy, and the install runs again.
This was my original Dockerfile, and I'd bet half of you have one like it:
FROM node:22-slim WORKDIR /app COPY . . RUN npm ci RUN npm run build CMD ["node", "dist/server.js"] It reads fine and builds fine. It also ties a 90-second install to every file in the repository.
How does Docker decide a COPY layer is cached?
For COPY and ADD, Docker checksums the contents of the files being copied. File modification times aren't part of that checksum, so touching a file without changing it won't break anything. Changing a single byte in any copied file will.
The checksum covers everything the instruction copies, and COPY . . copies the whole context minus whatever .dockerignore excludes. With no .dockerignore, that's every file on disk under your project root, including:
-
.git/, the entire repository history and its working files -
node_modules/from your host machine -
dist/,coverage/,.next/, and other build output -
.envfiles, which is a separate and worse problem
Any one of those changing is enough to make the build start over at COPY . ..
Why does .git break the Docker build cache without a commit?
Some files inside .git change constantly, and not only when you commit. The most important one is .git/index. Git keeps cached file stat information in it, and commands like git status can refresh that information and write the index back to disk, even when nothing is staged.
That means none of these needed a commit to break my cache:
- running
git statusin a terminal - my editor's Git integration polling the repo in the background
-
git fetch, which updatesFETCH_HEADand remote refs - switching branches and switching back, which leaves the files identical but changes
HEADhistory and the reflog
So two back-to-back builds with no code changes could still miss the cache, because something read the repo between them. That's why this felt random for so long: the cache wasn't randomly missing, it was following .git exactly.
Your image almost never needs .git. If you need a commit SHA inside the image, pass it in with --build-arg GIT_SHA=$(git rev-parse HEAD) instead of shipping the whole repo history.
How do I see what's in my Docker build context?
Build a throwaway image that copies the context and lists it. This shows you exactly what Docker received after .dockerignore was applied:
docker build --no-cache --progress=plain -f - . <<'EOF' FROM busybox COPY . /ctx RUN du -sh /ctx && find /ctx -maxdepth 2 | sort | head -80 EOF -f - reads the Dockerfile from stdin while . remains the context, so you don't need a temp file. --progress=plain prints the RUN output instead of collapsing it.
The first time I ran this, du reported a context of over a gigabyte for a service whose source is a few megabytes. Most of it was .git and two node_modules folders. You can also see the transfer at the top of a normal build in the transferring context line. If that number is large for a small app, it's coming from one of these folders.
Why doesn't node_modules in .dockerignore exclude nested folders?
.dockerignore doesn't match patterns the way .gitignore does. A bare node_modules line only matches node_modules at the root of the build context. Unlike .gitignore, it does not match packages/api/node_modules.
This is what got me after the first fix. I added node_modules to .dockerignore, the context shrank, and builds were still slow. My repo is a small workspace monorepo, and every package had its own node_modules that was still being sent.
Use **/ for anything that can appear at any depth:
# .dockerignore .git **/node_modules **/dist **/coverage **/.next **/*.log **/.env* .DS_Store Two more rules worth knowing:
- Docker reads
.dockerignorefrom the root of the build context, not from the folder that holds your Dockerfile. If you build withdocker build -f docker/api.Dockerfile ., the file belongs in.. - With BuildKit, a file named after your Dockerfile (for example
api.Dockerfile.dockerignore, placed next to it) takes priority over the root one. That's useful when two images built from the same context need different exclusions.
Does host node_modules actually break anything besides speed?
Yes. If your host's node_modules gets into the context and you COPY . . after npm ci, the host folder overwrites the one you just installed in the container.
On a Mac, that means you can end up with macOS-native binaries inside a Linux image. Packages with native code or platform-specific binaries (esbuild, sharp, bcrypt, and others) then fail at runtime or build time with errors about the wrong platform. The build passed on your machine, and the container still breaks.
Excluding **/node_modules fixes speed and correctness together.
What Dockerfile order keeps npm ci cached?
Copy the dependency manifests first, install, then copy the source. The install layer then depends only on package.json and package-lock.json, so it stays cached until your dependencies actually change.
# syntax=docker/dockerfile:1 FROM node:22-slim WORKDIR /app # 1. Only the files that decide what gets installed COPY package.json package-lock.json ./ # 2. Install. Cached until one of those two files changes. RUN --mount=type=cache,target=/root/.npm npm ci # 3. Everything else, filtered by .dockerignore COPY . . RUN npm run build CMD ["node", "dist/server.js"] The --mount=type=cache line keeps npm's download cache between builds on the same builder. Even when the lockfile does change and npm ci has to run, most tarballs come from the local cache instead of the registry. It needs BuildKit, which is the default builder in current Docker releases.
For a workspace monorepo, step 1 also has to copy every workspace package.json, because npm ci needs them to resolve the workspace graph. List them explicitly. It's tedious, but it's the only way to keep a change to one package's source from invalidating the install.
What changed after the fix?
On my machine, a source-only change now skips straight past npm ci and shows CACHED on that step. The build is down to the COPY . . plus npm run build, which takes seconds instead of most of a minute. The build context went from over a gigabyte to a few megabytes, so the transferring context line finishes almost instantly.
The README typo I started with now costs nothing, which is how it should have been from the start.
Quick checklist
- Add
.dockerignoreat the context root with.git,**/node_modules, build output, and**/.env*. - Run the busybox listing build above and confirm what's left in the context.
- Move
COPY package.json package-lock.json ./andRUN npm ciaboveCOPY . .. - Add
--mount=type=cache,target=/root/.npmto the install step. - Build twice with
--progress=plainand check thatnpm cisaysCACHEDthe second time.
So why does Docker re-run npm ci every build?
Docker re-runs npm ci every build when the install step sits below a COPY that includes files that change between builds. With COPY . . and no .dockerignore, that includes .git, where files like .git/index can be rewritten by a plain git status, and your host node_modules, which can also overwrite the container's platform-specific install. To fix it, copy package.json and package-lock.json first, run npm ci, then copy the source, and add a .dockerignore at the build context root that excludes .git, **/node_modules (with the **/ prefix, because a bare pattern only matches at the root), build output, and .env files.
Written by the developer behind Preterview, an interview prep platform.
