1.原理
Docker使用Cgroups完成对宿主机资源的管理和限制。
2.为什么需要限制
一般是限制CPU和内存,宿主机的资源是有限的,如过对于Docker中的容器不加以限制,那么会导致宿主机的负载过大导致宕机的可能,会影响到宿主机的功能。
3.图示
3.内存相关分配
3.1 查看命令详情
docker container run --help memory
[root@VM-0-7-centos docker]# docker container run --help|grep memory
--kernel-memory bytes Kernel memory limit
-m, --memory bytes Memory limit
--memory-reservation bytes Memory soft limit
--memory-swap bytes Swap limit equal to
memory plus swap: '-1'
--memory-swappiness int Tune container memory
3.2 配置容器最大使用内存
--memory bytes
如下,容器nginx2设置最大使用的内存为1G。
[root@VM-0-7-centos docker]# docker container run -d --name nginx2 --memory 1G nginx
1887eef326fd892e7833cd611c3f169455e315f7880b23266fcda40b1fa5603b
使用docker container stats nginx2
可查看该Docker使用的资源情况
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
1887eef326fd nginx2 0.00% 1.977MiB / 1GiB 0.19% 656B / 0B 0B / 4.1kB 3
发现它的内存LIMIT为1G
3.3 配置磁盘内存存储大小
--memory-swap
容器可以使用磁盘作为额外的内存(在已经超过最大内存时),大小为memory-swap的大小。但这个内存速度较为缓慢,只能在合适的业务场景中使用。
[root@VM-0-7-centos docker]# docker container run -d --name nginx2 --memory 1G --memory-swap 1G nginx
注意:配置swap必须配置--memory
。
3.4 设置容器不被kill
容器在使用内存超过限制之后,docker有权利将容器杀死,但有些容器服务很重要,不能被杀死。
配置--oom-kill-disable
为false
就能让容器无论如何都不会被docker杀死
4.CPU相关
4.1 最大使用CPU核数
如下设置最大使用1核CPU
--cpus
[root@VM-0-7-centos docker]# docker container run --name nginx2 -d --cpus 1 nginx
e8d4b705aed993af43f4dc3879b134c8bef0d4b4d5ed89e2a57a6ac122ce9bd6
4.2 最大使用CPU核数区间
--cpuset-cups
如下容器可以在cpu0 - cpu1之间执行
[root@VM-0-7-centos docker]# docker container run --name nginx2 -d --cpuset-cpus '0-1' nginx
154841354f99551534c695bd17695a9868d0bddf6ef84c5b07bbc6769915dda7
如下容器只能在cpu0和cpu1上执行
[root@VM-0-7-centos docker]# docker container run --name nginx2 -d --cpuset-cpus '0,1' nginx
154841354f99551534c695bd17695a9868d0bddf6ef84c5b07bbc6769915dda7
使用docker container stats nginx2
可查看该Docker使用的资源情况
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
1887eef326fd nginx2 0.00% 1.977MiB / 1GiB 0.19% 656B / 0B 0B / 4.1kB 3
发现它的内存LIMIT为1G
4.3 CPU相对权重
--cpu-shares
安装比例划分CPU使用
设置nginx1使用50%CPU
[root@VM-0-7-centos docker]# docker container run --name nginx1 -d --cpu-shares 50 nginx
154841354f99551534c695bd17695a9868d0bddf6ef84c5b07bbc6769915dda7
设置nginx2使用30%CPU
[root@VM-0-7-centos docker]# docker container run --name nginx2 -d --cpu-shares 30 nginx
154841354f99551534c695bd17695a9868d0bddf6ef84c5b07bbc6769915dda7
设置nginx3使用20%CPU
[root@VM-0-7-centos docker]# docker container run --name nginx3 -d --cpu-shares 30 nginx
154841354f99551534c695bd17695a9868d0bddf6ef84c5b07bbc6769915dda7