QA
Beginner LevelDocker & Deployment

How do Docker Multi-Stage Builds minimize image size and improve security?

❓ Interview Prompt: Write an optimized production Dockerfile for a Node.js/Next.js app using multi-stage builds and non-root users.

Multi-Stage Builds use multiple FROM statements in a single Dockerfile. Each stage is an isolated build environment — build tools, compilers, and devDependencies remain trapped in early stages and are never copied to the final runtime image.

Why This Matters:

•
A naive single-stage Node.js image can exceed 1.5 GB. A multi-stage alpine runtime image shrinks to ~150 MB.
•
Vulnerabilities in build tools (webpack, tsc, eslint) cannot be exploited at runtime because they don't exist in the final image.

Key Stages:

1
deps – install only production node_modules with npm ci --only=production.
2
builder – compile/build the application (runs npm run build).
3
runner – copy only compiled artifacts and production deps into a minimal Alpine image, then switch to a non-root user.

Code Implementation Example

dockerfile
# Stage 1: Install production dependencies only
FROM node:20-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

# Stage 2: Build the application
FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

# Stage 3: Minimal production runtime
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production

# Create non-root user for security
RUN addgroup --system --gid 1001 nodejs && \
    adduser  --system --uid 1001 nextjs

COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static

USER nextjs
EXPOSE 3000
CMD ["node", "server.js"]
💡Multi-stage production Dockerfile: build tools stay in stage 2, only the compiled output reaches stage 3.
🎯 Interview Key Takeaway

Multi-stage builds eliminate build-time dependencies from the final image, shrinking attack surface and image size by up to 90%.

#Docker#Multi-Stage#Security#DevOps#Beginner
Back to all Docker & Deployment Questions→

More Docker & Deployment Interview Questions

Beginner LevelDocker & Deployment

What is the difference between a Docker Container and a Virtual Machine (VM)?

Beginner LevelDocker & Deployment

What is the difference between a Docker Image and a Docker Container?

Beginner LevelDocker & Deployment

What are core Dockerfile instructions (FROM, WORKDIR, COPY, RUN, CMD, ENTRYPOINT)?