What is a multi-stage Dockerfile?
Answer
Multi-stage builds use multiple FROM instructions in a single Dockerfile. Each FROM starts a new build stage with its own base image. You can selectively copy artifacts from previous stages — leaving behind build tools, source code, and other unnecessary files. This produces much smaller, cleaner final images. Classic example — Node.js application: FROM node:20 AS builder\nWORKDIR /app\nCOPY package*.json ./\nRUN npm ci\nCOPY . .\nRUN npm run build\n\nFROM node:20-alpine AS production\nWORKDIR /app\nCOPY --from=builder /app/dist ./dist\nCOPY --from=builder /app/node_modules ./node_modules\nCOPY package.json .\nEXPOSE 3000\nUSER node\nCMD ["node", "dist/app.js"]. The builder stage compiles/builds the app; the production stage starts fresh from a minimal Alpine image and copies only the built output — no TypeScript compiler, dev dependencies, or source files. Result: final image might be 100MB instead of 800MB. Benefits: smaller attack surface (fewer packages = fewer vulnerabilities), faster image pushes/pulls, less storage. Build only a specific stage: docker build --target builder -t myapp:builder .. Copy from external image: COPY --from=nginx:1.25 /etc/nginx/nginx.conf /etc/nginx/nginx.conf.