Docker rebuilds npm install on every change

Reorder your COPY instructions to cache the dependency layer and builds get several times faster. How layer caching works and the common mistake.

While setting up a build stage for this blog, it bugged me that changing a single line of code forced the whole npm install to run again.

The cause

Docker caches one layer per COPY instruction — but a layer can only stay cached if every layer before it is unchanged.

# ❌ Copying all source first means a single post change
#    busts this layer, and npm install below it reruns too.
COPY . .
RUN npm install

The fix: copy dependency files first

# ✅ Copy only the package files first → if deps didn't change,
#    the install layer is served from cache.
COPY package*.json ./
RUN npm install
# then copy the source → only this and below rerun on source changes
COPY . .
RUN npm run build

As long as package.json is unchanged, the npm install layer is reused from cache.

What to remember

Put what changes often near the bottom of the Dockerfile. Moving rarely-changing dependency installs up top is the heart of layer caching.