How To Limit Resources For Docker Containers
Resource control is crucial when running multiple containers on shared infrastructure. Without proper limits, a single container can consume all available memory or CPU, affecting system stability. This guide shows you how to limit resources for Docker Containers with real-world examples.
Why Set Resource Limits?
By default, Docker containers can use as much CPU and RAM as the host system allows. This can lead to:
- Performance degradation of other containers or host processes
- Out-of-memory (OOM) crashes
- Unpredictable behavior in production environments
Setting resource limits helps isolate workloads and maintain performance across services.
Steps To Limit Resources For Docker Containers
Example: Running a Python App With Resource Limits
Let’s use a simple Python script that simulates CPU load:
cpu_stress.py
import time
while True:
[x**2 for x in range(10**6)] # CPU-intensive task
time.sleep(0.1)
Dockerfile
FROM python:3.11-slim
COPY cpu_stress.py .
CMD ["python", "cpu_stress.py"]
Build the image:
docker build -t stress-demo .

Run Without Limits (Baseline)
docker run --rm stress-demo
This container will consume as much CPU as it needs, unrestricted.
Set CPU and RAM Limits
Now, let’s restrict it:
docker run --rm \
--cpus="0.5" \ # Limit to half a CPU core
--memory="100m" \ # Limit RAM to 100MB
stress-demo

Breakdown:
--cpus="0.5"
: Limits the container to 50% of one CPU core.--memory="100m"
: Prevents the container from using more than 100MB of memory.
Try monitoring it with:
docker stats

You’ll see that the container respects your defined resource boundaries.
Additional Options
--memory-swap="150m"
: Sets total memory + swap limit.--memory-reservation="80m"
: Soft limit before Docker starts throttling.--cpuset-cpus="0,1"
: Binds container to specific CPU cores.--oom-kill-disable
: Prevents the container from being killed when it exceeds memory.
Best Practices
- Always define limits in production, especially on shared servers.
- Use monitoring tools like
docker stats
, Prometheus, or cAdvisor to observe usage. - Test your container behavior under constrained environments before deployment.
Docker makes it easy to control how much CPU and memory a container can consume. By setting appropriate limits, you can ensure that your applications stay stable and predictable—even in busy or resource-limited environments.
You can read more useful articles like How to Fix Timezone Issues in Docker Containers.
Follow us for the more helpful posts!
We hope this is a useful post for you.
Â