How to Limit Container Resources in Docker: Memory & CPU Limits
To limit container resources in Docker, use
--memory to restrict RAM and --cpus to limit CPU usage when running a container with docker run. For example, docker run --memory=500m --cpus=1.5 limits the container to 500 MB RAM and 1.5 CPU cores.Syntax
Docker provides resource limiting options when starting a container with docker run. The main flags are:
--memory: Limits the maximum memory the container can use (e.g., 500m for 500 MB).--cpus: Limits the number of CPU cores the container can use (e.g., 1.5 for one and a half cores).--memory-swap: Sets total memory + swap limit.--cpu-shares: Sets relative CPU weight for scheduling.
These flags help control how much system resources a container can consume.
bash
docker run --memory=500m --cpus=1.5 <image_name>
Example
This example runs an nginx container limited to 300 MB of memory and 0.5 CPU cores. It shows how to apply resource limits practically.
bash
docker run --rm --memory=300m --cpus=0.5 nginx
Output
Starting nginx container with memory limited to 300 MB and CPU limited to 0.5 cores.
Container runs and serves web pages with limited resource usage.
Common Pitfalls
Common mistakes when limiting container resources include:
- Setting memory limits too low causing the container to be killed by the system (OOM killer).
- Using
--cpu-sharesexpecting hard CPU limits; it only sets relative priority. - Not setting
--memory-swapproperly, which can allow swap usage beyond memory limit. - Forgetting to test container behavior under limits to avoid unexpected crashes.
bash
docker run --memory=100m nginx # May cause container to be killed if nginx needs more memory docker run --cpu-shares=512 nginx # Does NOT limit CPU to 50%, only priority docker run --memory=500m --memory-swap=1g nginx # Limits memory + swap to 1 GB total
Quick Reference
| Option | Description | Example |
|---|---|---|
| --memory | Limit max RAM usage | --memory=500m |
| --cpus | Limit CPU cores | --cpus=1.5 |
| --memory-swap | Limit RAM + swap | --memory-swap=1g |
| --cpu-shares | Set CPU priority weight | --cpu-shares=512 |
Key Takeaways
Use --memory and --cpus flags with docker run to limit container RAM and CPU usage.
Set memory limits carefully to avoid container crashes from out-of-memory errors.
--cpu-shares controls CPU priority, not hard limits; use --cpus for strict CPU limits.
Test containers under resource limits to ensure stable behavior.
Use --memory-swap to control total memory plus swap usage if needed.