Create a Dockerfile with multi-stage builds: first stage installs dependencies and builds, second stage copies only production files for smaller images. Use .dockerignore, optimize layer caching, and consider Node.js-specific best practices like running as non-root.
Docker Concepts:
Best Practices:
Optimization:
# Stage 1: Build
FROM node:20-alpine AS builder
WORKDIR /app
# Copy package files first (cache layer)
COPY package*.json ./
# Install ALL dependencies (including dev)
RUN npm ci
# Copy source and build
COPY . .
RUN npm run build
# Prune dev dependencies
RUN npm prune --production
# Stage 2: Production
FROM node:20-alpine AS production
WORKDIR /app
# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
adduser -S nodejs -u 1001
# Copy built files and production deps
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./
# Set ownership
RUN chown -R nodejs:nodejs /app
USER nodejs
# Environment
ENV NODE_ENV=production
ENV PORT=3000
EXPOSE 3000
# Health check
HEALTHCHECK --interval=30s --timeout=3s \
CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1
CMD ["node", "dist/index.js"]