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=
--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/