Skip to content
Docker

Multi-Stage Build

Build artifacts in one stage and copy them into a slim final image.

By EZ4Code Team
dockerfilemulti-stageoptimization

Code

# Dockerfile
FROM node:20 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY --from=builder /app/dist ./dist
USER node
CMD ["node", "dist/server.js"]

# Result: tiny production image without dev deps and source

Explanation

Multi-stage builds use multiple FROM lines to keep the final image small by copying only the artifacts needed from earlier stages. The builder stage compiles the code, while the runtime stage carries only production dependencies and the build output. This pattern dramatically reduces image size and attack surface.

More Docker Snippets