Beginner LevelDocker & Deployment
How do you set CPU and Memory limits on Docker containers (--memory, --cpus)?
❓ Interview Prompt: Explain Docker cgroup resource constraints — memory limits, CPU shares, OOM killer, and swap limits for production containers.
Without resource limits, a single runaway container can exhaust host RAM and starve all other processes — including the OS itself. Docker uses Linux cgroups to enforce resource boundaries.
Memory Limits:
•
--memory 512m — hard RAM cap. When exceeded, the Linux OOM Killer terminates the container process.•
--memory-swap 512m — total memory + swap. Setting equal to --memory disables swap.•
--memory-reservation 256m — soft limit, used for scheduling hints.CPU Limits:
•
--cpus="1.5" — limits to 1.5 CPU cores worth of compute time (uses CFS bandwidth throttling).•
--cpu-shares 512 — relative CPU weight in contention (default 1024). Lower = less CPU when contested.•
--cpuset-cpus="0,1" — pin container to specific CPU cores.Production Best Practice:
Always set both --memory and --cpus in production. In Kubernetes, these map directly to Pod resources.limits.
Code Implementation Example
bash
# Run container with explicit memory and CPU limits
docker run -d \
--name api \
--memory="512m" \
--memory-swap="512m" \
--cpus="1.0" \
--memory-reservation="256m" \
-p 3000:3000 \
myapp:latest
# In Docker Compose:
# services:
# api:
# image: myapp:latest
# deploy:
# resources:
# limits:
# cpus: '1.0'
# memory: 512M
# reservations:
# memory: 256M
# Monitor actual usage vs limits
docker stats api --no-stream
# CONTAINER CPU % MEM USAGE / LIMIT MEM %
# api 12.3% 243MiB / 512MiB 47.5%
# Check OOM kill events
docker inspect api --format '{{.State.OOMKilled}}'💡Setting hard memory (OOM killer) and CPU (CFS throttle) limits — essential for multi-tenant host stability.
🎯 Interview Key Takeaway
Always set --memory and --cpus in production. Unconstrained containers trigger OOM kills that crash entire host servers.
#Docker#cgroups#Memory Limits#CPU Limits#OOM Killer#Beginner
Back to all Docker & Deployment Questions→