Skip to main content

Setting Docker CPU and Memory Limits

Set Docker CPU and memory limits with cgroups, understand throttling versus OOMKills, and apply limits in docker run and Compose files.

44 Terms

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.

flowchart TD A[Container hits its limit] --> B{Which resource?} B -->|CPU| C[Throttled by cgroup] B -->|Memory| D[Kernel OOM killer] C --> E(Slower but still running) D --> F(Exit code 137) classDef neutral fill:#F1F5F9,color:#1E293B classDef warn fill:#FFEDD5,color:#1E293B classDef bad fill:#FEE2E2,color:#1E293B class A,B neutral class C,E warn class D,F bad

Keep these rules in mind:

  1. CPU is compressible: Exceeding the limit slows the container down but does not kill it.
  2. Memory is not compressible: Exceeding the limit kills the process, so memory limits need safety margin.
  3. Exit code 137 is ambiguous: It means SIGKILL, which can be an OOMKill or a manual docker kill. Check the OOMKilled flag 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.

Bash
docker run -d --name payment-api --memory=512m registry.devops.in/payment-api:3.1.0
# Confirm the value in bytes
docker inspect --format '{{.HostConfig.Memory}}' payment-api
# 536870912
# Disable swap for this container: total equals memory
docker 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 GB
docker 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 pressure
docker run -d --name payment-api-soft \
--memory=512m --memory-reservation=256m \
registry.devops.in/payment-api:3.1.0
Remember

--memory-reservation is 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.

Bash
# Allocate memory in 10 MB chunks inside a 50 MB container
docker run -d --name oom-test --memory=50m --memory-swap=50m python:3.12-slim \
python3 -c "
import time
x = []
while True:
x.append(' ' * 10_000_000)
print(f'Allocated {len(x) * 10} MB', flush=True)
time.sleep(0.2)
"
# Watch it die
docker logs -f oom-test
# Confirm the cause
docker inspect --format 'Exit={{.State.ExitCode}} OOMKilled={{.State.OOMKilled}}' oom-test
# Exit=137 OOMKilled=true
# The kernel logs the kill
sudo 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.

Bash
# Hard ceiling: at most 1.5 CPU cores of time
docker run -d --name order-api --cpus=1.5 registry.devops.in/order-api:2.0.0
# Relative weight: only matters when containers compete for CPU
docker run -d --name high-priority --cpu-shares=1024 registry.devops.in/search-api:5.2.0
docker 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 workloads
docker run -d --name trading-engine --cpuset-cpus="0,1" registry.devops.in/trading-engine:4.1.0
# Verify
docker inspect --format '{{.HostConfig.NanoCpus}}' order-api
# 1500000000
docker inspect --format '{{.HostConfig.CpusetCpus}}' trading-engine
# 0,1
How 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.

Bash
# Live view of all containers
docker stats
# One-shot snapshot for scripts
docker 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 v2
stat -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 restart
docker update --memory 1g --memory-swap 1g payment-api
docker update --cpus 2 payment-api
Tip

In docker stats, CPU percentage is relative to a single core, so a container with --cpus=1.5 can 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.

YAML
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:
Bash
docker compose up -d
# Verify the limits were actually applied
docker inspect --format '{{.HostConfig.Memory}} {{.HostConfig.NanoCpus}}' $(docker compose ps -q payment-api)
docker stats --no-stream
How 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.

Bash
# 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 runs
docker 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_throttled
docker run -d --name payment-api --cpus=0.75 --memory=600m registry.devops.in/payment-api:3.1.0

Production 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-swap equal to --memory for predictable behaviour.
  • Use --cpus for ceilings and --cpu-shares for 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 Mistake

Setting 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.

Security

Missing 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

Resources

Explore More in Docker Fundamentals and Container Lifecycle

All 4 Topics

Frequently Asked Questions

Is Setting Docker CPU and Memory Limits free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Setting Docker CPU and Memory Limits topic cover?

Set Docker CPU and memory limits with cgroups, understand throttling versus OOMKills, and apply limits in docker run and Compose files.

Found a mistake, an outdated step or a broken link?