Dev Overflow Logo

Dev Overflow

Global search

Search across questions, answers, users and tags.

Loading...
save

Why is my Docker build not using the cache when only my source changed?

clock icon

asked 3 months ago

message icon

1

eye icon

852

Every build reinstalls all dependencies even when I only edited one component. My Dockerfile:

1FROM node:22-alpine
2WORKDIR /app
3COPY . .
4RUN npm ci
5RUN npm run build
1FROM node:22-alpine
2WORKDIR /app
3COPY . .
4RUN npm ci
5RUN npm run build

1 Answer

COPY . . invalidates the cache for every layer beneath it whenever any file changes — including your one component. So npm ci reruns every time.

Copy the manifests first, install, then copy the source:

1FROM node:22-alpine
2WORKDIR /app
3COPY package.json package-lock.json ./
4RUN npm ci
5COPY . .
6RUN npm run build
1FROM node:22-alpine
2WORKDIR /app
3COPY package.json package-lock.json ./
4RUN npm ci
5COPY . .
6RUN npm run build

Now the install layer is only invalidated when the lockfile changes.

Add a .dockerignore too — without it node_modules and .next get sent to the daemon and can bust the cache through mtime changes alone:

1node_modules
2.next
3.git
1node_modules
2.next
3.git

1

of 1

Write your answer here

Introduce the problem and expand on what you've put in the title.

Top Questions