Dev Overflow Logo

Dev Overflow

Global search

Search across questions, answers, users and tags.

Loading...
save

Docker image for a Next.js app is 1.2GB — how do I shrink it?

clock icon

asked 2 months ago

message icon

1

eye icon

762

My Dockerfile is the naive one: copy everything, npm install, npm run build, npm start. The resulting image is over a gigabyte, which makes deploys painfully slow.

1FROM node:22
2WORKDIR /app
3COPY . .
4RUN npm install && npm run build
5CMD ["npm", "start"]
1FROM node:22
2WORKDIR /app
3COPY . .
4RUN npm install && npm run build
5CMD ["npm", "start"]

1 Answer

Two changes do most of the work: a multi-stage build, and Next's standalone output.

Set this in next.config.ts:

1export default { output: "standalone" }
1export default { output: "standalone" }

Then only copy the traced runtime into a slim final stage:

1FROM node:22-alpine AS deps
2WORKDIR /app
3COPY package*.json ./
4RUN npm ci
5
6FROM node:22-alpine AS builder
7WORKDIR /app
8COPY --from=deps /app/node_modules ./node_modules
9COPY . .
10RUN npm run build
11
12FROM node:22-alpine AS runner
13WORKDIR /app
14ENV NODE_ENV=production
15COPY --from=builder /app/.next/standalone ./
16COPY --from=builder /app/.next/static ./.next/static
17COPY --from=builder /app/public ./public
18CMD ["node", "server.js"]
1FROM node:22-alpine AS deps
2WORKDIR /app
3COPY package*.json ./
4RUN npm ci
5
6FROM node:22-alpine AS builder
7WORKDIR /app
8COPY --from=deps /app/node_modules ./node_modules
9COPY . .
10RUN npm run build
11
12FROM node:22-alpine AS runner
13WORKDIR /app
14ENV NODE_ENV=production
15COPY --from=builder /app/.next/standalone ./
16COPY --from=builder /app/.next/static ./.next/static
17COPY --from=builder /app/public ./public
18CMD ["node", "server.js"]

That typically lands around 150MB. Add a .dockerignore with node_modules and .next so the build context stays small too.

1

of 1

Write your answer here

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

Top Questions