docker系统资源限制
本文基于马哥的docker和k8s视频总结, 在此致谢马哥.

- 默认情况下容器无任何资源限制
- 对资源的限制依赖于内核的支持


限制容器使用内存


- 从物理内存ram和交换内存swap两方面做限制
- 在容器中使用
free
看到的swap和实际可用swap不是同一个
docker container
或docker create
时支持使用的参数:
-m or --memory=4m # 支持b, k, m, g等单位, 可单独使用, 指定容器最多可使用多少内存
--memory-swap * # 要想使用此选项, 必须要先使用-m选项
--memory-swappiness # 系统优化有此内核参数, 可用sysctl -a | grep swapiness查看
# 限制容器使用交换分区的倾向性, 值0~100
--memory-reservation # 预留的内存空间, 软限制
--oom-kill-disable true # 倘若某个容器特别重要, 则可把值设为true, 防止系统因
# OOM而把容器kill掉, 此参数必须配合-m选项才能使用
--oom-score-adj int # 此值从-1000~1000, 值越小, 越不会被优先kill掉
限制容器使用CPU


- 大多数系统在进程调度时使用的调度算法是CFS (完全公平调度器, 用于调度-20~19之间的进程)
docker container
或docker create
时支持使用的参数:
--cpu-shares 1024 # 按比例切分当前系统所有可用cpu资源
--cpus=<value> # 限制一个容器最多使用的cpu核数, --cpu=1.5表示最多使用
# 一个核加另外一个核百分之五十的资源
--cpuset-cpus 0,2 # 指定容器进程只能运行在哪个cpu上, 假如系统有4核, 那么内核对
# 应为0-3, 可以指定值为 0,2 表示运行在第一个, 第三个核上
--cpu-period=<value> # 限制最多使用cpu的时间
docker-ng (压测工具)
docker-stress-ng: Lighweight docker image for stress-ng
下一代压力测试工具
docker image pull lorel/docker-stress-ng # 拉取镜像
验证内存资源限制
docker container run --name stress1 -it --rm -m 256m lorel/docker-stress-ng --vm 2
-m 256m # 指定容器最多使用256m内存
--vm 2 # 启动两个worker进程, 每个默认占用256m内存
docker container top stress1 # 用该命令查看时会发现除主进程外有4个子进程
UID PID PPID C STIME TTY TIME CMD
root 15156 15139 0 01:29 pts/0 00:00:00 /usr/bin/stress-ng --vm 2
root 15192 15156 0 01:29 pts/0 00:00:00 /usr/bin/stress-ng --vm 2
root 15193 15156 0 01:29 pts/0 00:00:00 /usr/bin/stress-ng --vm 2
root 15374 15192 87 01:30 pts/0 00:00:05 /usr/bin/stress-ng --vm 2
root 15385 15193 82 01:30 pts/0 00:00:02 /usr/bin/stress-ng --vm 2
docker container stats # 实时显示容器的资源占用情况, 会发现容器使用的内存始终不会超过256m
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
296f349474ad stress1 185.98% 255.6MiB / 256MiB 99.85% 656B / 0B 57.9GB / 198GB 5
验证cpu资源限制
验证按比例切分当前系统所有可用cpu资源
# 开启两个shell, 在两个shell中分别跑其中一个container
docker container run --name stress1 -it --rm --cpu-shares 1024 lorel/docker-stress-ng --cpu 8
docker container run --name stress2 -it --rm --cpu-shares 512 lorel/docker-stress-ng --cpu 8
docker container stats # 会发现cpu使用量是2:1
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
71f3b807811f stress1 267.27% 26.47MiB / 3.84GiB 0.67% 656B / 0B 0B / 0B 9
320336a431ec stress2 130.87% 5.81MiB / 3.84GiB 0.40% 656B / 0B 0B / 0B 9
验证限制一个容器最多使用的cpu核数
docker container run --name stress1 -it --rm --cpus 1.5 lorel/docker-stress-ng --cpu 8
docker container stats # 此时或发现cpu的总体使用量接近于150%
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
bb3c87f28f6b stress1 147.27% 22.94MiB / 3.84GiB 0.58% 656B / 0B 0B / 0B 9
验证指定容器进程只能运行在哪个cpu上
docker container run --name stress1 -it --rm --cpuset-cpus 0,2 lorel/docker-stress-ng --cpu 8
docker container stats # 此时或发现cpu的总体使用量接近于200%, 因为指定只是用2个cpu
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
c51f5242d84a stress1 199.84% 31.59MiB / 3.84GiB 0.80% 656B / 0B 0B / 0B 9
网友评论