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?
0
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
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?
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
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
node:22-slim instead.