Container Foundations · 8 min read · Intermediate
Multi-Stage Builds & Security
Shrink production Docker images by 80% with multi-stage builds and run processes as a non-root USER.
What you'll learn
- Use FROM ... AS builder and COPY --from=builder to ship only compiled output
- Drop root privileges with USER node or a dedicated non-root user
- Pin major/minor image tags (node:20-alpine) instead of floating :latest
A multi-stage Dockerfile compiles your app in a full SDK stage (AS builder) and copies only the final binary or dist/ folder into a tiny runtime stage (nginx:alpine or distroless), stripping out build tools, compilers, and source code from production.
Fill-in-the-Blank Exercise
Multi-Stage Copy
Name the first stage builder and copy /app/dist from it into Nginx.
FROM node:20-alpine builder
WORKDIR /app
RUN npm run build
FROM nginx:alpine
COPY --=builder /app/dist /usr/share/nginx/htmlLive Multi-Stage Inspection Lab
Bashmultistage.sh
Expected OutputClick “Run Live” to compile with GNU Bash
1:FROM node:20-alpine AS builder 6:FROM nginx:1.27-alpine 7:COPY --from=builder /app/dist /usr/share/nginx/html
Check Your Understanding
Score: 0 / 1
1. What is the main advantage of a multi-stage Docker build?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.