Resource Limits
When you notice a container is using too many resources, and you don’t have the ability to “fix” the underlying code immediately, you can limit the resources the container is allowed to use at the infrastructure level.
The docker run command provides flags to set these limits:
--memory: Limit the memory available to the container (e.g.,512m,1g).--cpus: Limit the CPU time available to the container (e.g.,0.5for half a core,2.0for two cores).
Applying CPU Limits
Let’s run the same stress-ng container as before, but this time strictly limit its CPU usage to 0.25 (1/4th of a single CPU core):
docker run -d --cpus="0.25" --name cpu-stress alexeiled/stress-ng --cpu 2 --timeout 10m
--cpus="0.25"is the Docker flag that limits the container’s access to the host machine’s CPU.--cpu 2is an argument passed to thestress-ngprogram inside the container, telling it to try and use 2 cores.
If you run docker stats now, you will notice that the container’s CPU usage hovers around 25% of a single core, rather than consuming a full core or more. The Docker daemon strictly enforces the limit!
Being able to monitor and limit container resources is crucial for maintaining stable and healthy environments.