answersLogoWhite

0

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

User Avatar

Himanshi kaur

Lvl 8
3w ago

What else can I help you with?