Docker Resource Management
Resource management ensures that containers do not use excessive resources.
CPU Management
# Limit CPU (1.5 cores)
docker run -d --cpus="1.5" myapp
# Set CPU shares (relative weight)
docker run -d --cpu-shares=512 myapp
# Pin to specific CPUs
docker run -d --cpuset-cpus="0,1" myapp
Memory Management
# Limit memory (512 MB)
docker run -d --memory="512m" myapp
# Limit memory + swap
docker run -d --memory="512m" --memory-swap="1g" myapp
# Memory reservation
docker run -d --memory-reservation="256m" myapp
Use Case: Application Resources
version: '3.8'
services:
api:
build: ./backend
deploy:
resources:
limits:
cpus: '1.0'
memory: 512M
reservations:
cpus: '0.5'
memory: 256M
database:
image: postgres:15
deploy:
resources:
limits:
cpus: '2.0'
memory: 2G
reservations:
cpus: '1.0'
memory: 1G
redis:
image: redis:7-alpine
deploy:
resources:
limits:
cpus: '0.5'
memory: 256M
Monitoring Resources
# Real-time stats
docker stats
# Stats for specific containers
docker stats api database redis
# Export stats
docker stats --no-stream --format \
"table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"
Everyday Use Case
Case: A container is using excessive CPU.
# View resource usage
docker stats
# Limit CPU
docker update --cpus="1.0" api
# Limit memory
docker update --memory="512m" api
OOM Killer
# Disable the OOM killer
docker run -d --oom-kill-disable --memory="512m" myapp
# Adjust the OOM score
docker run -d --oom-score-adj=-500 myapp
Best Practices
- Set resource limits: For every container
- Monitor usage: Use docker stats
- Use healthchecks: For problem detection
- Scale horizontally: Instead of vertical scaling
Conclusion
Resource management is important for system stability. Set limits for every container and monitor usage regularly.