1. 程式人生 > >docker的memory和cpu資源限制

docker的memory和cpu資源限制

這裡僅針對docker本身,不涉及任何編排工具compose或者k8s等。

按照慣例,官文擼起來。

重要的部分是一些選項,用來限制資源大小。

Memory
Most of these options take a positive integer, followed by a suffix of b, k, m, g, to indicate bytes, kilobytes, megabytes, or gigabytes.

-m or --memory= The maximum amount of memory the container can use. If you set this option, the minimum allowed value is 4m (4 megabyte).
--oom-kill-disable By default, if an out-of-memory (OOM) error occurs, the kernel kills processes in a container. To change this behavior, use the --oom-kill-disable option. Only disable the OOM killer on containers where you have also set the -m/--memory option. If the -m flag is not set, the host can run out of memory and the kernel may need to kill the host system’s processes to free memory.

多數選項值都是正整數,單位是b, k, m, g,分別表示 bytes, kilobytes, megabytes, 和 gigabytes。

-m or --memory= 指定一個容器能使用的最大記憶體,預設不允許小於4m。
--oom-kill-disable 預設如果發生OOM異常,核心會kill掉容器中的程序。可以使用這個選項來改變這種行為。只在設定了-m記憶體限制的容器上有效。如果沒有設定-m,宿主機會OOM,然後核心會需要kill宿主機的程序來釋放記憶體。


CPU
By default, each container’s access to the host machine’s CPU cycles is unlimited. You can set various constraints to limit a given container’s access to the host machine’s CPU cycles. Most users use and configure the default CFS scheduler.

The CFS is the Linux kernel CPU scheduler for normal Linux processes. Several runtime flags allow you to configure the amount of access to CPU resources your container has. When you use these settings, Docker modifies the settings for the container’s cgroup on the host machine.

--cpus=<value> Specify how much of the available CPU resources a container can use. For instance, if the host machine has two CPUs and you set --cpus="1.5", the container is guaranteed at most one and a half of the CPUs. 
--cpuset-cpus Limit the specific CPUs or cores a container can use. A comma-separated list or hyphen-separated range of CPUs a container can use, if you have more than one CPU. The first CPU is numbered 0. A valid value might be 0-3 (to use the first, second, third, and fourth CPU) or 1,3 (to use the second and fourth CPU).

預設,每個容器能使用的系統cpu資源是沒有限制的。多數使用者使用預設的CFS排程器來配置。
CFS是linux用於程序的核心cpu排程器。有一些執行時選項可以用來限制容器可以使用的cpu資源,這些配置會修改宿主機上容器的cgroup設定。

--cpus= 指定一個容器可用的cpu資源的大小。例如,如果宿主機有兩個cpu,那麼--cpus="1.5"表示可以使用1.5個cpu。
--cpuset-cpus 限制一個容器能使用指定的cpu或cpu核心。可以用逗號分隔符表示單獨的哪幾個,或者連字元(中橫線)表示範圍。從0開始計數,第一個cpu記為0。1, 3表示使用第二個和第四個cpu。1-3表示使用第二三四個cpu。

一個簡單示例:

# If you have 1 CPU,  the following command guarantees the container at most 50% of the CPU every second.

docker run -it --cpus=".5" debian:jessie /bin/bash

參考:
https://docs.docker.com/config/containers/resource_constraints/