What are Multi-Stage Builds?
Multi-Stage Builds allow you to use multiple FROM statements in a single Dockerfile. Only the final stage is used as the output image — keeping the final image small and clean.
Why Use Multi-Stage Builds?
- Produce smaller production images (without build tools)
- Keep development tools out of the final image
- Improve security by reducing attack surface
Example 1: Node.js App
# Stage 1: Build
FROM node:18-alpine AS builder
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
RUN npm run build
# Stage 2: Production
FROM node:18-alpine AS production
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package.json .
RUN npm install --production
EXPOSE 3000
CMD ["node", "dist/index.js"]
docker build -t my-node-prod .Example 2: Go App
# Stage 1: Build Go binary
FROM golang:1.21 AS builder
WORKDIR /app
COPY . .
RUN go build -o myapp .
# Stage 2: Minimal runtime
FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/myapp .
EXPOSE 8080
CMD ["./myapp"]
Final image is just a few MBs — no Go compiler included.
Example 3: PHP Laravel
# Stage 1: Composer dependencies
FROM composer:2 AS composer-build
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install --no-dev --optimize-autoloader
# Stage 2: Final image
FROM php:8.2-fpm-alpine
WORKDIR /var/www/html
COPY --from=composer-build /app/vendor ./vendor
COPY . .
EXPOSE 9000
CMD ["php-fpm"]Comparing Image Sizes
docker build -t app-fat .
docker build -t app-slim -f Dockerfile.multistage .
docker images | grep app
Output:
app-fat latest 900MB
app-slim latest 85MB
Key Syntax
| Syntax | Meaning |
|---|---|
FROM image AS stagename | Name a build stage |
COPY --from=stagename | Copy files from a previous stage |
docker build --target stagename | Build up to a specific stage |
Summary
- Multi-stage builds use multiple FROM statements in one Dockerfile
- Only the final stage is included in the output image
- Results in smaller, more secure production images
- Use
COPY --from=stagenameto transfer artifacts between stages
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
