Course contentsShow
← Cloud and Infrastructure
Lesson 1020 of 2,98920. Docker in DepthFree lesson

Multi-Stage Builds Introduction

Using multiple FROM statements to separate build-time and runtime dependencies.

Multi-Stage Builds Introduction

What you'll learn: How to use multiple FROM statements in a single Dockerfile to cleanly separate build-time dependencies from runtime dependencies.

The Core Problem

When building containerized applications, you often need tools during the build phase (like compilers, testing frameworks, or package managers) that you don't need in the final runtime image. Without multi-stage builds, these bulky build tools end up in your production image, making it unnecessarily large and increasing your attack surface.

How Multi-Stage Builds Work

A multi-stage build lets you write multiple FROM instructions in one Dockerfile. Each FROM starts a new build stage with its own base image. You build your application in one stage with all the tools you need, then copy only the compiled artifacts into a clean, minimal final stage.

Think of it like cooking: you use mixing bowls, whisks, and measuring cups to prepare a cake (build stage), but you only serve the finished cake on a clean plate (runtime stage) — the kitchen tools stay behind.

Simple Structure

# Stage 1: Build stage
FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

# Stage 2: Runtime stage
FROM node:18-slim
WORKDIR /app
COPY --from=builder /app/dist ./dist
CMD ["node", "dist/index.js"]

Notice the AS builder naming the first stage, and --from=builder referencing it. The final image only contains the slim Node runtime and built artifacts — no source code, no development dependencies.

Key Takeaway: Multi-stage builds use multiple FROM statements to separate build tooling from runtime, producing smaller, more secure production images by copying only essential artifacts between stages.