How to Limit CPU Resources in Docker Compose
When running containers in production, proper CPU resource management is crucial for maintaining stable performance. Here's a comprehensive guide on how to limit CPU resources in Docker Compose.
Complete Example
Here's a Docker Compose configuration demonstrating various CPU resource management options:
services:
api:
image: node:alpine
deploy:
resources:
limits:
cpus: '0.50' # Container can use at most 50% of a CPU
memory: '512M' # Maximum memory limit
reservations:
cpus: '0.25' # Guaranteed CPU resources
memory: '256M' # Minimum memory reservation
cpu_shares: 1024 # Relative CPU weight (default: 1024)
cpuset: '0,1' # Restrict to CPU cores 0 and 1
worker:
image: python:alpine
deploy:
resources:
limits:
cpus: '0.75'
cpu_shares: 512 # Half the priority of api service
cache:
image: redis:alpine
cpus: '0.3' # Direct CPU limit (simpler alternative)
Understanding CPU Options
- cpus
- Simplest way to limit CPU usage
- Value of
1.0
means one CPU core - Example:
cpus: '0.5'
limits to 50% of one CPU
- cpu_shares
- Sets relative weight between containers
- Default value is 1024
- Only affects containers competing for CPU
- deploy.resources
- Modern way to specify resource constraints
- Supports both limits and reservations
- Used in Swarm mode and recent Compose versions
- cpuset
- Pins container to specific CPU cores
- Useful for performance-critical applications
- Format:
"0,1"
or"0-3"
Monitoring
Monitor CPU usage with:
docker stats
# or for specific service
docker-compose top service_name
Best Practices
- Start with conservative limits (
cpus: '0.5'
) - Use
cpu_shares
for relative prioritization - Monitor and adjust based on actual usage
- Document resource allocation decisions
Common Issues
- Performance Issues: If service is slow, check if CPU limits are too restrictive
- Uneven Distribution: Use
cpu_shares
to balance load between services - High CPU Usage: Monitor with
docker stats
and adjust limits accordingly
For more advanced resource management, consider using Kubernetes, which offers more sophisticated orchestration capabilities.