Lesson 20 / 26

Multi-Stage Builds

Compile in one stage, ship only the runtime artifacts in a smaller 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:20 AS build
WORKDIR /app
COPY . .
RUN npm install && npm run build

# --- runtime stage ---
FROM node:20-alpine
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY package.json .
RUN npm install --production
CMD ["node", "dist/server.js"]