Container Resource Limits
Set CPU and memory limits on Docker containers. Learn about resource constraints, OOM killer behavior, CPU shares, and monitoring resource usage.
Container Lifecycle
Detailed Explanation
Memory Limits
Set hard memory limits to prevent a container from consuming all host memory:
# Limit to 512MB RAM
docker run -d --memory=512m my-app
# Memory + swap limit
docker run -d --memory=512m --memory-swap=1g my-app
# Disable swap entirely
docker run -d --memory=512m --memory-swap=512m my-app
OOM Killer Behavior
When a container exceeds its memory limit, the Linux OOM killer terminates it. Control this with:
# Disable OOM killer (container hangs instead of being killed)
docker run -d --memory=512m --oom-kill-disable my-app
# Adjust OOM priority (-1000 to 1000, lower = less likely to be killed)
docker run -d --memory=512m --oom-score-adj=-500 my-app
CPU Limits
# Limit to 1.5 CPUs
docker run -d --cpus=1.5 my-app
# CPU shares (relative weight, default 1024)
docker run -d --cpu-shares=512 my-app
# Pin to specific CPU cores
docker run -d --cpuset-cpus="0,1" my-app
Monitoring Resource Usage
# Real-time stats
docker stats my-app
# Single snapshot
docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}" my-app
# Check limits via inspect
docker inspect --format '{{.HostConfig.Memory}}' my-app
In Docker Compose
services:
api:
image: my-api
deploy:
resources:
limits:
cpus: '2.0'
memory: 1G
reservations:
cpus: '0.5'
memory: 256M
Use Case
Preventing runaway containers from consuming all host resources in production, setting up fair resource sharing in multi-tenant environments, and configuring appropriate limits for CI/CD build containers.