Lesson 22 / 28
Multi-Stage Builds
Shrink images with multi-stage builds that compile in one stage and copy only runtime artifacts to the final image.
Why bother?
Build tools, compilers, and source code often aren't needed at runtime, but a single-stage Dockerfile ships them anyway — bloating the image and its attack surface.
Build stage + runtime stage
Name a stage with AS, then COPY --from=<stage> pulls only the built artifact into a slim final image — the compiler and dev dependencies never make it in.
# --- build stage ---
FROM node:22 AS build
WORKDIR /app
COPY . .
RUN npm install && npm run build
# --- runtime stage ---
FROM node:22-alpine
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY package.json .
RUN npm ci --omit=dev
CMD ["node", "dist/server.js"]