Docker Best Practices¶
🏆 Learning Objectives
- Follow Docker best practices
- Write production-ready Dockerfiles
- Organize Docker projects
- Implement security and optimization
Comprehensive best practices for Docker in production.
Best Practices Summary
- Use specific image tags, not
latest - Run as non-root user
- Minimize layers and image size
- Use multi-stage builds
- Set resource limits
- Implement health checks
- Scan for vulnerabilities
- Document everything
Production Readiness
A production-ready Docker setup includes: security hardening, resource limits, health checks, logging, monitoring, backups, and documentation. Don't skip any of these - they're all critical for reliable operations.
Image Best Practices¶
Base Images¶
Layer Optimization¶
# ✅ Combine RUN commands
RUN apt-get update && \
apt-get install -y package && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
# ❌ Multiple RUN commands
RUN apt-get update
RUN apt-get install -y package
Multi-stage Builds¶
# ✅ Use multi-stage builds
FROM node:16 AS builder
# ... build steps ...
FROM node:16-alpine
COPY --from=builder /app/dist ./dist
Security Best Practices¶
Non-Root User¶
Minimal Base Images¶
Scan Images¶
Runtime Best Practices¶
Resource Limits¶
Health Checks¶
Restart Policies¶
Networking Best Practices¶
User-Defined Networks¶
DNS Resolution¶
Data Management¶
Named Volumes¶
# ✅ Use named volumes
docker run -v mydata:/data myapp
# ❌ Bind mounts (when possible)
docker run -v /host/path:/data myapp
Backup Strategy¶
# ✅ Regular backups
docker run --rm -v mydata:/data \
-v $(pwd):/backup alpine \
tar czf /backup/backup.tar.gz /data
Monitoring Best Practices¶
Logging¶
# ✅ Configure logging
services:
app:
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
Metrics¶
CI/CD Best Practices¶
Build Optimization¶
Image Tagging¶
Documentation¶
Dockerfile Comments¶
# Install system dependencies
RUN apt-get update && apt-get install -y \
python3 \
pip
# Copy application code
COPY . /app
README Files¶
Checklist¶
Image Checklist¶
- Use specific base image tags
- Minimize layers
- Use multi-stage builds
- Remove unnecessary packages
- Use .dockerignore
- Scan for vulnerabilities
Container Checklist¶
- Run as non-root user
- Set resource limits
- Configure health checks
- Use restart policies
- Enable logging
- Set up monitoring
Security Checklist¶
- Scan images regularly
- Use minimal base images
- Run as non-root
- Limit capabilities
- Use secrets management
- Keep images updated
Exercises¶
- Refactor a Dockerfile following best practices
- Set up comprehensive monitoring
- Implement security scanning in CI/CD
- Create production-ready compose file
Previous: Advanced Topics