1. How do Docker Multi-Stage Builds minimize image size and improve security?
β Context: 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:
Key Stages:
node_modules with npm ci --only=production.npm run build).# 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 builds eliminate build-time dependencies from the final image, shrinking attack surface and image size by up to 90%.