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

  1. Limit memory with --memory.
  2. Limit CPU with --cpus.
  3. Limit swap with --memory-swap.
  4. 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 reservations in 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.