What is a multi-stage Docker build, and how does it produce a smaller final image for a Node.js application?
Short answer
A multi-stage build uses multiple FROM statements in a single Dockerfile, where an earlier stage can install build tools, dev dependencies, and compile/transpile code (like TypeScript), and a later, final stage copies only the resulting build artifacts and production…
Advertisement
AModel answer
A multi-stage build uses multiple FROM statements in a single Dockerfile, where an earlier stage can install build tools, dev dependencies, and compile/transpile code (like TypeScript), and a later, final stage copies only the resulting build artifacts and production dependencies from that earlier stage -- leaving all the build-time tooling and dev dependencies behind, producing a much smaller and more secure final image that doesn't ship an entire compiler toolchain to production.
# Build stage
FROM node:20 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Final, lean production stage
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's production Docker image shrinks from over 1.2GB to under 200MB after switching to a multi-stage build, since the TypeScript compiler, dev dependencies, and full source tree used only during the build no longer need to be shipped in the final runtime image at all.
Likely follow-ups
- How does a smaller final image size specifically improve both deployment speed and the application's attack surface?
- How would you further reduce the final image size by also excluding dev-only npm packages from the copied node_modules?
Related topics