Docker Best Practices for Production π³
Multi-Stage Builds: Cut Image Size by 70%
FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
FROM node:18-alpine
COPY --from=builder /app/node_modules ./node_modules
COPY . .
USER node
EXPOSE 3000
CMD ["node", "app.js"]
Result: 900MB β 120MB image size
Security Hardening
Run as Non-Root
RUN useradd -m appuser
USER appuser
Remove Package Manager
RUN apt-get purge -y --auto-remove apt-get
Scan for Vulnerabilities
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy image myapp:latest
Performance Optimization
- Layer Caching - Order commands from least to most frequently changed
- Use .dockerignore - Exclude unnecessary files
- Minimize Layers - Combine RUN commands with &&
# Bad: 3 layers
RUN apt-get update
RUN apt-get install curl
RUN rm -rf /var/lib/apt/lists/*
# Good: 1 layer
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
Container Networking
Health Checks
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f http://localhost:3000/health || exit 1
Port Exposure
EXPOSE 3000 8080
Production Checklist
- β Non-root user
- β Security scanning passed
- β Health checks defined
- β Resource limits set
- β Logging configured
- β No secrets in image
Master these practices and your deployments will be rock solid. π
Top comments (0)