Why Multi-Stage Docker Builds are Mandatory for Production
Early container practices compiled applications and packaged runtime files into a single monolithic Docker container image. This resulted in massive 1.5 GB images laden with build tools (gcc, g++, python-dev, npm build caches, git, and devDependencies) that increase container startup latency and expose a vast attack surface.
Multi-stage Docker builds solve this problem completely:
- Build Stage (
AS builder): Compiles TypeScript, installs devDependencies, and builds production bundles. - Runner Stage: Starts fresh from a stripped-down Alpine or Distroless base image (~5-30MB) and copies only the compiled output and production dependencies.
Docker Layer Caching Best Practices
Docker executes each instruction in a Dockerfile sequentially, caching intermediate layers. If a layer changes, all subsequent layers must be rebuilt from scratch.
RUN npm install
RUN npm ci --only=production
COPY . .
Crucial Docker Security Hardening Rules
- Never Run as Root: Specify
USER nodeor create an unprivileged user (RUN addgroup -S appgroup && adduser -S appuser -G appgroup). - Always Include a .dockerignore: Exclude
.envsecrets,.gitfolders, and localnode_modulesso they are never baked into image layers. - Implement Container Healthchecks: Configure
HEALTHCHECK --interval=30s --timeout=3s CMD wget -qO- http://localhost:3000/health || exit 1so Docker and Kubernetes can automatically restart hung containers.
Frequently Asked Questions (FAQ)
What is the difference between npm install and npm ci in Docker?
npm ci (Clean Install) strictly installs exact dependency versions from package-lock.json without modifying the lockfile. It is significantly faster and guarantees 100% reproducible Docker builds across team members and CI/CD pipelines.
What is the difference between CMD and ENTRYPOINT?
ENTRYPOINT specifies the fixed executable to run when the container starts. CMD provides default arguments to the entrypoint that can be easily overridden by passing CLI arguments to docker run.