Docker Best Practices

Docker best practices I follow:

Dockerfile Optimization

# Use specific versions, not 'latest'
FROM node:18-alpine

# Create non-root user
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001

# Copy package files first for better caching
COPY package*.json ./
RUN npm ci --only=production

# Copy source code
COPY . .
RUN chown -R nextjs:nodejs /app

USER nextjs

# Use ENTRYPOINT for better signal handling
ENTRYPOINT ["dumb-init", "--"]
CMD ["node", "server.js"]

.dockerignore Optimization

node_modules
npm-debug.log
.git
.gitignore
README.md
.env
.nyc_output
coverage
.vscode
*.log
dist
build

Multi-stage Builds

FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:18-alpine AS production
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
CMD ["node", "dist/server.js"]

Security Tips

  • Never run as root user
  • Use official base images
  • Keep images updated
  • Scan for vulnerabilities
  • Use secrets management