Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set CPU limit in Docker Compose

I got a on-prem server which I would like to deploy many micro-services. I'm using a docker-compose file to declare all services and would like to set the cpu limit. I refer the docs below: https://docs.docker.com/compose/compose-file/ My docker compose file is like:

version: "3.7"
services:
  redis:
    image: redis:alpine
    deploy:
      resources:
        limits:
          cpus: '2'
          memory: 256M
        reservations:
          cpus: '0.25'
          memory: 64M
  service1:
    image: service1 image
    deploy:
      resources:
        limits:
          cpus: '2'
          memory: 512M
        reservations:
          cpus: '0.25'
          memory: 64M

...

I'm confused to calculate the cpus limits. For example, the cpu is 8 cores. There are 20 microservices. Is there any way I can calculate the cpu limit of each service? Or any formulas to do so?

----- UPDATE ------ To make it clearer, my main point here is CPU limit. It is because I'd like to send alert if the CPU of one microservice is using 80% of CPU for that microservice. If I don't set the cpu limit, is it true that the microservice CPU usage will be the same with host CPU usage? I don't use Docker's Swarn but Docker only.

Any ideas are really appreciated.

Thanks,

like image 615
Kenny Tai Huynh Avatar asked Apr 17 '26 03:04

Kenny Tai Huynh


1 Answers

Welcome to 2022. I'm using version 1.29 of docker-compose with a yaml version of 3.9

If I set my yml file as follows:

version: '3.9'

services:

    astro-cron:
        build: ./cron
        image: astro-cron
        restart: unless-stopped
        volumes:
          - /home/docker-sync/sites/com/cron:/astro/cron
        environment:
          - TZ=America/Phoenix
        mem_limit: 300m
        mem_reservation: 100m
        cpus: 0.3

It nicely limits the container cpu to 30% of the machine. The memory limits kill the container if exceeded, which will auto-restart.

The cpu limit does not kill anything, just holds.

I'm not using docker swarm.

PS. To address the other answer of having an overcommitted cpu not being a problem. It IS a problem if one of your containers is an unimportant background job, and another is a customer facing web site or database. Unless someone can explain why that wouldn't be the case.

like image 92
blissweb Avatar answered Apr 20 '26 12:04

blissweb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!