Docker Resource Limits: Control Container CPU and Memory

·1042 words

A container can use the CPU and memory available to its Docker host by default. When several containers run at once, resource boundaries can reduce the risk of one workload crowding out the host. Limits set too low, however, can slow an application or cause it to be terminated. Using Docker Engine 29.x, Docker Compose, and Swarm, this guide shows how to set CPU and memory limits, verify that they took effect, and investigate problems caused by tight limits.

Common commands at a glance
#

CommandPurpose
docker run --cpus=1 --memory=512m ...Limit a container to one CPU’s worth of quota and 512 MiB of memory
docker inspect --format ... CONTAINERInspect the container’s configured CPU and memory limits
docker stats CONTAINERObserve resource usage in real time
docker compose configCheck the rendered Compose service configuration
docker compose up -dCreate or update services from a Compose file
docker service ps SERVICEInspect Swarm service task states

CPU and memory limits are different
#

--cpus=1.5 sets a CPU-time quota, allowing a container to use up to roughly 1.5 CPUs’ worth of processing time over an interval. It does not reserve 1.5 dedicated cores or guarantee that much compute is always available. Under host contention, the container still competes with other processes.

--memory=512m sets a hard limit on memory available to a container. Once processes reach it, further memory allocations can trigger the kernel’s out-of-memory (OOM) handling and terminate a process in the container. The memory limit is not a safe application heap size: the runtime, shared libraries, and other processes also consume container memory.

Before setting limits, check which Engine the current Docker context targets and inspect the host resources. A remote Docker context sends commands to the remote Engine.

Shell
docker context show
docker info

With Docker Desktop or OrbStack, containers run in a Linux virtual machine. The VM’s resource configuration also constrains what the Engine can allocate. Do not treat all memory in the macOS or Windows host as available to the Linux Engine.

Limit a single container
#

The following command starts a short-lived Python process with a quota of 0.5 CPUs and 128 MiB of memory. --rm removes only the container created by this command after the process exits.

Shell
docker run --rm --cpus=0.5 --memory=128m python:3.11-slim \
  python -c 'print("resource limits configured")'

A successful exit means the process completed within these limits; it does not mean these values suit another application. Choose limits from measurements of normal workload, concurrency, and host headroom. Do not copy example values into production without testing.

For a longer-running container, give it a dedicated name and inspect the saved configuration:

Shell
docker run -d --name resource-demo --cpus=0.5 --memory=128m \
  python:3.11-slim python -m http.server 8000
docker inspect --format 'NanoCpus={{.HostConfig.NanoCpus}} Memory={{.HostConfig.Memory}}' resource-demo
docker stats --no-stream resource-demo

NanoCpus=500000000 represents a quota of 0.5 CPUs, and Memory=134217728 represents 128 MiB. docker stats shows current usage, not the configured limit; output formatting varies by Docker version. After confirming resource-demo is the container created for this exercise, stop and remove it:

Shell
docker stop resource-demo
docker rm resource-demo

Set service limits in Compose
#

A Compose file can express CPU and memory limits under a service’s deploy.resources.limits. This example applies limits to a local practice service:

YAML
services:
  web:
    image: python:3.11-slim
    command: ["python", "-m", "http.server", "8000"]
    ports:
      - "127.0.0.1:8000:8000"
    deploy:
      resources:
        limits:
          cpus: "0.50"
          memory: 128M

From the directory containing this file, inspect the rendered configuration before starting the service:

Shell
docker compose config
docker compose up -d
docker compose ps
docker compose stats --no-stream

Support and behavior of Compose resource fields depend on the implementation and deployment target. With local Compose, check the rendered configuration and inspect the created container to confirm the effective limits. Do not assume a limit took effect just because it appears in YAML. In the Compose Specification, reservations are resource requests, not hard limits; local Engine and Swarm have different scheduling semantics for reservations.

When finished, run this from the directory containing the Compose file:

Shell
docker compose down

This stops and removes the project’s containers and default network, but not its images. Do not use a global prune command as a substitute for targeted cleanup.

Limits and reservations in a Swarm Stack
#

A Swarm Stack uses deploy.resources on a service. limits cap the resources available to each task. reservations tell the scheduler how much allocatable resource a node must have to place a task. A reservation is not a hard cap on container usage or host-level isolation.

YAML
services:
  web:
    image: registry.example.com/team/web:1.0
    deploy:
      resources:
        limits:
          cpus: "0.50"
          memory: 256M
        reservations:
          cpus: "0.25"
          memory: 128M

registry.example.com/team/web:1.0 is a placeholder image reference. Replace it with an image that every cluster node can pull. Stack files use the format supported by docker stack deploy; a successful docker compose config does not prove that Swarm parses every field or behaves identically. See Docker Swarm and Stack for the deployment workflow.

Swarm uses reservations when scheduling. If no node can satisfy a reservation, a task may remain Pending. Inspect the service tasks and node resources instead of repeatedly increasing the replica count:

Shell
docker service ps STACK_web
docker node ls

When a container slows down or exits
#

  • The container is slow: Use docker stats to inspect CPU and memory, then check host and peer-container load. A CPU quota throttles the workload; it does not allocate more compute.
  • The container exits or restarts: Check its state with docker ps -a and inspect application output with docker logs CONTAINER. If memory is near the limit, inspect the exit state and Engine events; raising the CPU quota will not resolve an OOM termination.
  • A service cannot be scheduled: In Swarm, inspect docker service ps SERVICE errors and check available node resources, constraints, and reservations. More replicas increase resource demand.
  • The configuration looks unexpected: Confirm the current Docker context and deployment mode, then inspect the rendered Compose configuration or the container’s effective settings with docker inspect.

CPU and memory limits are resource-management controls, not a complete security-isolation or capacity-planning solution. Leave headroom for the host, system services, and workload spikes, and monitor application latency, errors, and restarts.

References
#