Docker Compose resource limits and reservations

How to set CPU and RAM limits and reservations in a docker-compose file to prevent host overload and improve container security.

Proper resource management on a server is critical — not only to handle workloads efficiently, but also to limit the blast radius of a cyberattack. When deploying containers, you can assign and cap CPU and RAM usage per container.

In your docker-compose.yml files, you can define both limits and reservations for each service:

  • reservations = guarantee a minimum amount of resources for a container
  • limits = prevent a container from exceeding a given amount of resources

Add the following block to your docker-compose.yml for each service you want to constrain:

yaml
services:
  my-service:
    deploy:
      resources:
        limits:
          cpus: "0.15"
          memory: 128m
        reservations:
          cpus: "0.05"
          memory: 64M

You can use any combination:

  • limits only
  • reservations only
  • both limits and reservations

The CPU limit (cpus: "0.15") means the container can use at most 15% of a single CPU core on the host. Other CPU scheduling options exist (e.g. cpu_shares, cpu_quota), but in most cases letting the OS and kernel handle scheduling is the right call.

Running the stack#

Once your .yml file is ready, start your containers with:

bash
# Docker Compose v2 (recommended, built into Docker)
docker compose up -d

Note: Since Docker Compose v2, the deploy.resources block is supported natively without any extra flags. If you are still using Docker Compose v1 (the standalone docker-compose binary), you need to add --compatibility to enable this block outside of Swarm mode.

To monitor resource usage in real time, run:

bash
docker stats

The Memory column will reflect the limits and reservations defined in your compose file. CPU limits are enforced by the kernel but are not directly shown in docker stats.

Source

Stay Updated

Subscribe to the RSS feed or follow for new articles.

Related articles

Latest in #docker