Dockerizing Node.js for Production: Small, Secure, Fast Images

A good image is small, secure, and starts fast

Containers are the standard way to ship Node.js services. A careless Dockerfile produces 1 GB images running as root. A good one is small, secure, and fast to build.

A Production Dockerfile

# ---- build stage ----
FROM node:22-slim AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev

# ---- runtime stage ----
FROM node:22-slim
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
COPY --from=build --chown=node:node /app/package.json ./
USER node
EXPOSE 3000
HEALTHCHECK CMD node -e "fetch('http://localhost:3000/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
CMD ["node", "dist/server.js"]

Use the current Active LTS Node version.

Why Each Line Matters

  • Multi-stage — build tools stay out of the final image
  • npm ci — reproducible installs from the lockfile
  • Copy package*.json first — Docker caches the install layer until dependencies change
  • USER node — never run as root
  • node directly in CMD — not npm start, so signals reach your process

.dockerignore

node_modules
.git
.env
coverage
*.log

Never copy .env files or secrets into images.

Graceful Shutdown

Kubernetes and Docker send SIGTERM before killing a container:

process.on('SIGTERM', () => {
  server.close(() => process.exit(0));
});

Finish in-flight requests and close DB connections cleanly.

Security

  • Scan images for vulnerabilities (Docker Scout, Trivy, or your registry's scanner)
  • Use minimal base images (slim or distroless)
  • Pin versions and rebuild regularly for patches
  • Pass secrets via environment variables or a secret manager

Configuration

Follow twelve-factor principles: configuration from environment variables, logs to stdout, stateless processes.

Your Dockerfile is production code. Review it like any other code.

Arivanandhan Chitheshwaran