What is a multi-stage Docker build, and why is it commonly used for Node.js applications?
Short answer
A multi-stage build uses multiple FROM statements in a single Dockerfile, where an early stage (with full build tools, dev dependencies, and a compiler) builds or compiles the application, and a later, much leaner final stage copies only the necessary build output and production…
Advertisement
AModel answer
A multi-stage build uses multiple FROM statements in a single Dockerfile, where an early stage (with full build tools, dev dependencies, and a compiler) builds or compiles the application, and a later, much leaner final stage copies only the necessary build output and production dependencies -- resulting in a significantly smaller final image that doesn't carry the weight of dev dependencies, build tools, or source files not needed at runtime.
FROM node:20 AS builder
WORKDIR /app
COPY . .
RUN npm ci && npm run build
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
CMD ["node", "dist/server.js"]Real-world example
A TypeScript-based API reduces its final Docker image size from over 1GB to around 150MB by using a multi-stage build, compiling TypeScript to JavaScript in a builder stage and copying only the compiled output and production dependencies into the slim final image.
Likely follow-ups
- Why does a smaller final image matter for deployment speed and security?
- How do you decide what to copy from the builder stage versus rebuild from scratch in the final stage?
Related topics