How to manage Docker resource limits?
· Category: Docker
Short answer
Use Docker resource constraints to limit CPU, memory, swap, and block I/O. Set them at runtime with flags or in Compose files to prevent noisy neighbor problems.
Steps
- Limit memory with
--memory. - Limit CPU with
--cpus. - Limit swap with
--memory-swap. - Configure I/O with
--device-read-bps.
Example
docker run -d --memory="512m" --cpus="1.5" myapp
Docker Compose:
services:
app:
image: myapp
deploy:
resources:
limits:
cpus: '1.5'
memory: 512M
reservations:
cpus: '0.5'
memory: 256M
Tips
- Always set memory limits to prevent OOM kills of the host.
- Use
reservationsin Swarm to guarantee minimum resources. - Monitor actual usage before setting tight limits.
Common issues
- Java and Node.js applications may crash if memory limits are lower than their heap size.
- CPU throttling can cause latency spikes.
- The host kernel must support the requested cgroup limits.