Overview and What You Will Learn
By default a Docker container can use all the CPU and memory on its host. You limit it with cgroup-backed flags such as --memory and --cpus. The two limits behave differently: a container that exceeds its CPU limit is throttled and keeps running, while a container that exceeds its memory limit is killed by the kernel with exit code 137.
In this lab you will:
- Set hard and soft memory limits and control swap
- Trigger and diagnose an OOMKill on purpose
- Set CPU limits with
--cpus,--cpu-shares, and--cpuset-cpus - Monitor usage and detect CPU throttling
- Apply limits in Docker Compose
- Choose limits from measurements instead of guesses
Why This Matters in Production
On a shared host, one leaking service can take every neighbour down with it. Think of a platform team at a company like Razorpay or Shopify running dozens of services on one EC2 instance: without limits, a payment container with a memory leak can starve the database and cache containers, and the kernel may kill the wrong process. Limits turn one container's bug into that container's problem alone.
Core Principles
Docker enforces limits with Linux cgroups, a kernel feature that caps the resources of a group of processes. Docker creates one cgroup per container and writes your limits into it.
Keep these rules in mind:
- CPU is compressible: Exceeding the limit slows the container down but does not kill it.
- Memory is not compressible: Exceeding the limit kills the process, so memory limits need safety margin.
- Exit code 137 is ambiguous: It means SIGKILL, which can be an OOMKill or a manual
docker kill. Check theOOMKilledflag to tell them apart.
Detailed Step-by-Step Practical Lab
How to Set a Memory Limit and Control Swap
The --memory flag sets a hard ceiling, and --memory-swap sets the combined total of memory plus swap. If you set --memory but not --memory-swap, a container can use swap equal to its memory limit (twice the limit in total) when the host has swap enabled.
docker run -d --name payment-api --memory=512m registry.devops.in/payment-api:3.1.0 # Confirm the value in bytesdocker inspect --format '{{.HostConfig.Memory}}' payment-api# 536870912 # Disable swap for this container: total equals memorydocker run -d --name payment-api-noswap \ --memory=512m --memory-swap=512m \ registry.devops.in/payment-api:3.1.0 # Allow 512 MB RAM plus 512 MB swap: total of 1 GBdocker run -d --name payment-api-swap \ --memory=512m --memory-swap=1g \ registry.devops.in/payment-api:3.1.0 # Soft limit: enforced only when the host is under memory pressuredocker run -d --name payment-api-soft \ --memory=512m --memory-reservation=256m \ registry.devops.in/payment-api:3.1.0Remember
--memory-reservationis a soft limit that Docker applies when the host is short on memory. It is not a guaranteed allocation or a scheduling hint outside orchestrators.
How to Trigger and Diagnose an OOMKill
An OOMKill happens when a container tries to allocate more memory than its limit allows. Reproducing one in a safe test teaches you exactly what the evidence looks like.
# Allocate memory in 10 MB chunks inside a 50 MB containerdocker run -d --name oom-test --memory=50m --memory-swap=50m python:3.12-slim \ python3 -c "import timex = []while True: x.append(' ' * 10_000_000) print(f'Allocated {len(x) * 10} MB', flush=True) time.sleep(0.2)" # Watch it diedocker logs -f oom-test # Confirm the causedocker inspect --format 'Exit={{.State.ExitCode}} OOMKilled={{.State.OOMKilled}}' oom-test# Exit=137 OOMKilled=true # The kernel logs the killsudo dmesg | grep -i "killed process"How to Set CPU Limits With --cpus, --cpu-shares, and --cpuset-cpus
Use --cpus for a hard ceiling, --cpu-shares for relative priority under contention, and --cpuset-cpus to pin a container to specific cores. They solve different problems and can be combined.
# Hard ceiling: at most 1.5 CPU cores of timedocker run -d --name order-api --cpus=1.5 registry.devops.in/order-api:2.0.0 # Relative weight: only matters when containers compete for CPUdocker run -d --name high-priority --cpu-shares=1024 registry.devops.in/search-api:5.2.0docker run -d --name low-priority --cpu-shares=512 registry.devops.in/report-batch:1.9.0# Under contention, high-priority gets about twice the CPU time.# When the host is idle, either container can use all available CPU. # Pin to specific cores for latency-sensitive workloadsdocker run -d --name trading-engine --cpuset-cpus="0,1" registry.devops.in/trading-engine:4.1.0 # Verifydocker inspect --format '{{.HostConfig.NanoCpus}}' order-api# 1500000000docker inspect --format '{{.HostConfig.CpusetCpus}}' trading-engine# 0,1How to Monitor Usage and Detect CPU Throttling
docker stats shows live usage, but it does not show throttling. For that you read the container's cgroup cpu.stat file, where a rising nr_throttled means the CPU limit is slowing the application.
# Live view of all containersdocker stats # One-shot snapshot for scriptsdocker stats --no-stream --format "{{.Name}}: CPU={{.CPUPerc}} MEM={{.MemUsage}} ({{.MemPerc}})"# order-api: CPU=45.2% MEM=420MiB / 512MiB (82.0%) # Which cgroup version is the host using? cgroup2fs means v2stat -fc %T /sys/fs/cgroup # Check throttling counters (cgroup v2, systemd cgroup driver)ID=$(docker inspect -f '{{.Id}}' order-api)cat /sys/fs/cgroup/system.slice/docker-$ID.scope/cpu.stat# nr_periods 5400# nr_throttled 1320 <- high ratio means the CPU limit is too tight# throttled_usec 48200000 # Change limits on a running container without a restartdocker update --memory 1g --memory-swap 1g payment-apidocker update --cpus 2 payment-apiTipIn
docker stats, CPU percentage is relative to a single core, so a container with--cpus=1.5can legitimately show up to 150%.
How to Set Resource Limits in Docker Compose
Compose applies limits from deploy.resources, with limits as the hard ceiling and reservations as the soft guarantee. Docker Compose v2 honours these in normal, non-Swarm use.
services: payment-api: image: registry.devops.in/payment-api:3.1.0 ports: - "8080:8080" deploy: resources: limits: cpus: "1.5" memory: 512M reservations: memory: 256M order-api: image: registry.devops.in/order-api:2.0.0 deploy: resources: limits: cpus: "2" memory: 1G db: image: postgres:16-alpine volumes: - pgdata:/var/lib/postgresql/data environment: POSTGRES_PASSWORD: ledger_dev_pw deploy: resources: limits: cpus: "2" memory: 2G volumes: pgdata:docker compose up -d # Verify the limits were actually applieddocker inspect --format '{{.HostConfig.Memory}} {{.HostConfig.NanoCpus}}' $(docker compose ps -q payment-api)docker stats --no-streamHow to Choose the Right Limits
Choose limits by measuring the container under realistic load, then add a safety margin. A guessed number is the most common cause of random OOMKills.
# 1. Run the service without limits and apply a realistic load test (k6, wrk, or Locust)docker run -d --name measure-api registry.devops.in/payment-api:3.1.0 # 2. Sample usage while the test runsdocker stats --no-stream measure-api# NAME CPU % MEM USAGE# measure-api 35.2% 380MiB # 3. Memory: observed peak plus 25 to 50 percent# 380 MiB x 1.5 = 570 MiB, so set 600m# 4. CPU: allow headroom above the observed peak, then watch nr_throttleddocker run -d --name payment-api --cpus=0.75 --memory=600m registry.devops.in/payment-api:3.1.0Production Best Practices & Common Pitfalls
- Set a memory limit on every production container: It is the only reliable protection against a leaking service taking down a host.
- Measure before you set: Use load tests and peak usage, not intuition.
- Disable or control swap deliberately: Set
--memory-swapequal to--memoryfor predictable behaviour. - Use
--cpusfor ceilings and--cpu-sharesfor priority: Shares alone never cap anything. - Watch
nr_throttled: Tight CPU limits can add latency without any crash to point at. - Alert on
OOMKilled: Treat repeated kills as a sizing or leak problem. - Keep Docker and Kubernetes limits aligned: The same cgroup mechanism backs both.
Docker flags map directly onto Kubernetes fields:
| Docker | Kubernetes |
|---|---|
--memory=512m |
resources.limits.memory: 512Mi |
--memory-reservation |
resources.requests.memory |
--cpus=1.5 |
resources.limits.cpu: 1500m |
--cpu-shares |
resources.requests.cpu |
Common MistakeSetting a memory limit from gut feeling, such as 512 MB for an API that needs 800 MB under real load. The result is intermittent OOMKills that look like application bugs.
SecurityMissing limits are a denial-of-service risk on shared hosts. Even a trusted service with a memory leak can starve every other container, so always set limits.
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| Limit memory | docker run --memory=512m image |
| Disable swap | docker run --memory=512m --memory-swap=512m image |
| Limit CPU | docker run --cpus=1.5 image |
| Pin to cores | docker run --cpuset-cpus="0,1" image |
| Check OOMKilled | docker inspect --format '{{.State.OOMKilled}}' name |
| Live usage | docker stats --no-stream |
| Change limits live | docker update --memory 1g --memory-swap 1g name |
| Symptom | Likely cause | Fix |
|---|---|---|
Exit code 137 with OOMKilled=true |
Memory limit exceeded | Raise the limit or fix the leak |
Exit code 137 with OOMKilled=false |
Manual docker kill or SIGKILL |
Check who sent the signal |
| Service slow, no crash | CPU throttling | Check nr_throttled and raise --cpus |
| Host runs out of memory | Containers without limits | Set limits on every container |
docker update memory error |
Swap limit lower than memory | Update --memory and --memory-swap together |