CloudOps Hub
📦 Multi-Stage Production Pattern

Production Dockerfile for Node.js

A secure, multi-stage Node.js container setup using Alpine Linux, non-root user execution, and optimal layer caching.

Dockerfile Node 20 Alpine
# 1. Dependency installation stage
FROM node:20-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

# 2. Production runner stage
FROM node:20-alpine AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV PORT=3000

# Run container as unprivileged user for security
USER node

# Copy dependencies and application source
COPY --chown=node:node --from=deps /app/node_modules ./node_modules
COPY --chown=node:node . .

EXPOSE 3000

CMD ["node", "server.js"]

Key Best Practices Implemented

  • Layer Caching: Package manifests are copied before application code to prevent re-installing node_modules on code changes.
  • Non-root User: Executes under the built-in node user instead of root, reducing container breakout risk.
  • Production Only: Uses npm ci --only=production to omit development dependencies like test suites and compilers.