Multi-stage builds in Docker are a way to make Docker images smaller, cleaner, and faster.
Simple idea:
Instead of building everything in one big step, Docker lets you use multiple steps (stages) inside one Dockerfile.
Each stage can use a different base image.
Why it is used?
When you build an app, you often need:
Tools to compile/build the app (like Maven, Node, GCC)
But not those tools when you actually run the app
Multi-stage builds help you:
👉 Build the app in one stage
👉 Copy only the final result to another stage
👉 Leave unnecessary files behind
Easy example:
# Stage 1: Build stage
FROM node:18 AS builder
WORKDIR /app
COPY . .
RUN npm install && npm run build
# Stage 2: Final stage
FROM nginx:alpine
COPY --from=builder /app/build /usr/share/nginx/html
What is happening here?
Stage 1 uses Node.js to build the app
Stage 2 uses Nginx to serve only the built files
Final image does NOT include Node.js or build tools
Benefits:
✔ Smaller image size
✔ Faster deployment
✔ More secure (fewer tools inside final image)
✔ Cleaner structure
Peter Docker goes by Docker.
Advantages of multistage sampling?
Mary Docker is 5' 6".
Ralph Docker died in 1910.
Ralph Docker was born in 1855.
Ludford Docker was born in 1860.
Ludford Docker died in 1940.
Ian Docker was born in 1969.
Colin Docker was born in 1925.
Robert Docker was born in 1918.
Robert Docker died in 1992.
Dudley Docker died in 1910.