DEV3 Technologies home

DEV3 Developer Forum

How do I build a small production Docker image for a Next.js or Node.js app?

DevOps helpSolved0 views
dev3 ·

My Node image is 1.4 GB because it contains dev dependencies and build tools. How do I use a multi-stage Dockerfile to shrink it and avoid running as root?

#docker#nodejs#multi-stage

0

1 reply

dev3 · Accepted answer

Build in one stage, copy only what you need into a slim runtime stage.

# syntax=docker/dockerfile:1
FROM node:22-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci

FROM node:22-alpine AS build
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
RUN npm prune --omit=dev

FROM node:22-alpine AS runtime
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build --chown=node:node /app/package.json ./
COPY --from=build --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]

For Next.js, set output: 'standalone' in next.config and copy .next/standalone, .next/static and public into the runtime stage; start with node server.js. The standalone output includes only the traced dependencies and is much smaller.

Why it works

  • The runtime stage never sees compilers, tests, or source maps unless you copy them.
  • Copying package*.json first lets Docker cache the npm ci layer until dependencies change.
  • USER node stops the process running as root.

Also add a .dockerignore:

node_modules
.git
.env*
.next
dist
Dockerfile

Without it, COPY . . sends your local node_modules and secrets into the build context.

Pitfalls

  • Alpine uses musl; native modules (sharp, bcrypt) may need the matching platform binaries. If you hit errors, use node:22-slim instead.
  • Pin versions by tag or digest for reproducible builds.
  • Never bake secrets into image layers; pass them at runtime.
0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.