1. Introduction

In this short tutorial, we'll learn how to limit Docker container memory and CPU usage through Docker Compose file. In some cases, this can be very useful, for example when we have limited resources and microservice architecture with one of the services with a tendency to expand its resource consumption. This would potentially block or slow down other services, so we'll show here how to prevent this.

2. Limit Memory And CPU Usage With the docker-compose File

Docker memory usage limitation can be achieved per container using docker run command but also using docker-compose files. It's important to mention that the format and options will vary among versions of docker-compose. We'll cover cases for both version 2 and version 3 and newer.

2.1. Limit Resources With Version 2 of docker-compose

In older versions of docker-compose syntax, we can put the memory and CPU limits on the same level as the service's main properties:

service:
  image: nginx
  mem_limit: 1024m
  mem_reservation: 256M
  cpus: 0.5
  ports:
    - "80:80"


To create and run configured containers, we need to run the docker-compose command:

$ docker-compose up

2.2. Versions 3 and Newer With Docker Swarm

For versions 3 and newer, the notation is a bit different. Resource limits parameters are placed under deploy/resources node. 

In the example, we will give the Nginx service limit of half of CPU and 1024MB of memory, and reservation of a quarter of CPU and 256MB of memory. Let's see how does this look like:

services:
  service:
    image: nginx
    deploy:
        resources:
            limits:
              cpus: 0.50
              memory: 1024M
            reservations:
              cpus: 0.25
              memory: 256M

To use this deploy block we need to use docker stack deploy command that will deploy a stack to the swarm:

$ docker stack deploy --compose-file docker-compose.yml my_stack


3. Check and Verify Docker Container Memory and CPU Usage

Since we set the memory and CPU limits, we can verify them using the docker stats command:

$ docker stats

CONTAINER ID        NAME                                             CPU %               MEM USAGE / LIMIT   MEM %               NET I/O             BLOCK I/O           PIDS
17071c2f2dc8        goos_stack_service.1.p37ad21r1qih16ynif94sk2zj   0.00%               2.578MiB / 1024MiB   0.50%               936B / 0B           0B / 0B             2

4. Summary

In this tutorial, we learned how to limit Docker's access to the host's resources using docker-compose file. Also, we learned how to verify docker container memory and CPU usage. Besides docker-compose file, we can also set these limits through the docker run command.