Dockerdockermulti-stageoptimizationsecurityproduction-ready
Multi-Stage Docker Build
Production Dockerfile with multi-stage builds for minimal image size, security hardening, non-root users, and health checks.
title: "Multi-Stage Docker Build" description: "Production Dockerfile with multi-stage builds for minimal image size, security hardening, non-root users, and health checks." category: "Docker" language: "yaml" tags: ["docker", "multi-stage", "optimization", "security", "production-ready"] createdAt: "2025-02-10" updatedAt: "2025-03-01"
Overview
A production-ready multi-stage Dockerfile that separates dependency installation, building, and runtime into isolated stages. The final image contains only production artifacts, reducing size by 80%+ and eliminating build-time security vulnerabilities.
Code
FROM node:20-alpine AS builder
COPY . .
RUN npm run build
FROM node:20-alpine AS runner
COPY --from=builder /app/.next/standalone ./
CMD ["node", "server.js"]Notes
- Stage separation means build dependencies (compilers, dev tools) never reach production
dumb-initensures proper PID 1 signal handling (SIGTERM forwarding to child processes)- Non-root user (
appuser) follows the principle of least privilege HEALTHCHECKenables container orchestrators to detect unhealthy instances- Alpine base (~5MB) significantly reduces image size vs Debian-based images (~300MB)
- Separate
npm ci --only=productioncreates a lean node_modules for the final stage