⚡ ~/naveed Interview Prep
⚡ Portfolio Home 👤 About Naveed Bio & Credentials 📫 Contact Naveed Get In Touch ✍️ Engineering Blog Deep Dives 🎯 Interview Hub 1,000+ Scenarios ☸️ Kubernetes Mastery Hub 24 Modules 🎮 DevOps Arcade & Quizzes Subnet Blitz ⚡ 🗺️ DevOps Roadmaps PDFs & Guides 🤖 Morpheus Analysis AI Quant ↗ 🛠️ Developer Tools Utilities 🧪 Labs & Experiments 📄 Interactive CV & Certs 🔗 All Links & Socials ⚡ Join The Dispatch (Weekly SRE Newsletter) →
← Back to All Docker & Containers Interview Questions Scenario 42 of 159 in Docker & Containers
Senior DevOps / SRE [L2] Docker Production Scenario [L2]
🎯 Target Role / Context: Docker Scenario #42 (L2) · Docker

Q: How do you set resource limits for a Docker Compose service?

To set resource limits for a Docker Compose service, add deploy.resources.limits with cpus and memory to the service in compose.yaml. Docker Compose v2 applies these on docker compose up, while reservations declare a minimum.

#Docker #L2 #Containers #Linux
🎙️ Candidate Opening & Architectural Context
"To <strong>set resource limits for a Docker Compose service</strong>, add <code>deploy.resources.limits</code> with <code>cpus</code> and <code>memory</code> to the service in <code>compose.yaml</code>. Docker Compose v2 applies these on <code>docker compose up</code>, while reservations declare a minimum. Interviewers ask this to test whether you know the Compose Specification syntax, how limits behave at runtime (CPU throttling versus memory OOM kills), and how to verify enforcement. Mentioning the older <code>mem_limit</code> style shows you can read legacy files."
Advertisement
⚡ Recommended Practice Lab

Want to master this scenario in a live sandbox? KodeKloud's Docker Certified Associate (DCA) Hands-On Lab Course covers this exact problem with hands-on terminal drills.

🛠️ Production Runbook & Step-by-Step Resolution

Direct Answer: To <strong>set resource limits for a Docker Compose service</strong>, add <code>deploy.resources.limits</code> with <code>cpus</code> and <code>memory</code> to the service in <code>compose.yaml</code>. Docker Compose v2 applies these on <code>docker compose up</code>, while reservations declare a minimum. Interviewers ask this to test whether you know the Compose Specification syntax, how limits behave at runtime (CPU throttling versus memory OOM kills), and how to verify enforcement. Mentioning the older <code>mem_limit</code> style shows you can read legacy files.

1️⃣

Mental model: limits, reservations and what they do

Compose maps these keys to the same cgroup controls as docker run flags. Remember that limits protect the host and neighbouring services, so a missing limit on one container is a risk to every other container on that machine.

  • limits.cpus: a hard cap in CPU units, for example "0.5" is half a core, enforced by CFS throttling.
  • limits.memory: a hard cap. If the process exceeds it the kernel OOM killer terminates it and Docker reports exit code 137.
  • reservations: a soft minimum used for scheduling in Swarm. On a single host, a memory reservation acts as a soft limit under memory pressure.
  • Legacy keys: mem_limit, cpus, mem_reservation and pids_limit at service level are still supported by the Compose Specification.
  • Where it is enforced: limits are applied by the Docker Engine through cgroups on the host running the container, so they work the same in a laptop or a single-server deployment as they do for plain docker run.
2️⃣

Hands-on: set resource limits for a Docker Compose service

A complete example with CPU, memory and process limits.

services:
  api:
    image: registry.example.com/my-api:2.0
    deploy:
      resources:
        limits:
          cpus: "0.50"
          memory: 512M
        reservations:
          cpus: "0.25"
          memory: 256M
    pids_limit: 200

  worker:
    image: registry.example.com/my-worker:2.0
    cpus: 1.0          # legacy-style service-level keys
    mem_limit: 1g
  • Quote CPU values: write cpus: "0.50" as a string for portability.
  • Apply: run docker compose up -d. Changing limits recreates the container.
  • Preview the merged config: docker compose config shows what Compose will actually apply.
  • Swap and PIDs: memswap_limit and pids_limit at the service level cap swap use and fork bombs.
  • Memory plus swap: by default a memory limit may allow equal swap on some hosts, which delays OOM kills but slows the app badly. Set memswap_limit equal to the memory limit to disable extra swap.
Pro Tip: Do not set both <code>deploy.resources.limits.memory</code> and <code>mem_limit</code> for the same service with different values. Compose rejects conflicting definitions in many versions, so pick one style.
Advertisement
3️⃣

Verify the limits are enforced

Confirm what Docker applied, not only what the file says.

docker compose up -d
docker compose config | grep -A4 limits
docker stats --no-stream --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}'
# NAME      CPU %   MEM USAGE / LIMIT
# app-api-1 0.4%    120MiB / 512MiB
docker inspect --format '{{.HostConfig.NanoCpus}}' app-api-1
  • Live usage: docker stats --no-stream shows MEM USAGE / LIMIT, which should read 512MiB for api.
  • Inspect HostConfig: docker inspect --format '{{.HostConfig.Memory}} {{.HostConfig.NanoCpus}}' <container> prints bytes and nano-CPUs, here 536870912 500000000.
  • OOM check: docker inspect --format '{{.State.OOMKilled}} {{.State.ExitCode}}' <container> returns true 137 after a memory kill.
  • Stress test: run a memory hog in a staging container to see the kill behaviour before production does.
  • Docker Desktop: containers share the resources assigned to the Desktop VM, so a service limit above the VM allocation is meaningless. Raise the VM memory in settings first.
4️⃣

Failure modes and version caveats

Most surprises come from syntax history and runtime semantics. Check each symptom against the evidence before changing anything.

  • Compose v1 and the deploy key: old docker-compose 1.x ignored deploy outside Swarm unless run with --compatibility. Compose v2 (docker compose) honours it.
  • Silent OOM kills: a container restarting every few minutes with exit code 137 is usually hitting its memory limit. Raise it or fix the leak.
  • Runtime awareness: JVM, Node and Go may size heaps from host memory. Set JVM flags such as -XX:MaxRAMPercentage so the heap fits inside the cgroup limit.
  • Throttled latency: a tight CPU cap throttles bursts. Check for slow requests when CPU looks low.
  • Sizing method: run a realistic load test, record peak working set, and set the limit with headroom while keeping the reservation near typical usage.
5️⃣

Production practice: defaults and observability

Make sizing a measured, reviewed decision.

  • Measure first: base limits on observed peak usage from docker stats or cAdvisor with headroom, not guesses.
  • Use extension fields: define common limits once with a YAML anchor under an x- key and reuse it in services.
  • Alert: track memory near limit, OOMKilled events and CPU throttling in Prometheus.
  • Orchestrators: in Kubernetes translate these to resources.requests and resources.limits in the pod spec.
  • Profiles per environment: keep dev with generous limits in an override file such as compose.override.yaml and enforce stricter production values in compose.prod.yaml.
💡 The Senior SRE Gold Nugget (Key Architectural Takeaway)
"Pro-Tip: Verify limits with <code>docker inspect</code> and <code>docker stats</code> after <code>up</code>, and treat exit code 137 with <code>OOMKilled=true</code> as the signal that a memory limit is too low or the app leaks."
⚡ 60-Second Elevator Pitch Talking Points
  • I set <code>deploy.resources.limits</code> with cpus and memory in the Compose file, plus reservations, and apply it with <code>docker compose up -d</code>.
  • I confirm with <code>docker compose config</code>, <code>docker stats</code> and <code>docker inspect</code> for HostConfig.Memory and OOMKilled.
  • I size from measured peaks, align runtime heap settings with the limit and alert on OOM kills and CPU throttling.
⛔ Critical Candidate Mistakes to Avoid in This Scenario

Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:

  1. Relying on deploy limits with Compose v1 The legacy docker-compose 1.x ignored deploy outside Swarm, so containers ran unlimited. Use Compose v2.
  2. Setting memory limits below the runtime's heap needs The JVM or Node may try to exceed the cgroup limit and get OOM killed, even though the host has plenty of RAM.
  3. Unquoted or wrong CPU units cpus is a fraction of cores, not a percentage, so 50 means fifty cores. Use a quoted decimal like "0.5".
  4. Never checking exit codes Exit 137 with OOMKilled true is the only clear sign that limits killed the process. Without checking it, restarts look like random crashes.
Advertisement
Want more Docker & Containers scenarios?
Explore our complete collection of scenario-based Docker & Containers interview runbooks.
Browse All Docker & Containers Questions →