027、限制容器对内存的使用(2019-01-22 周二)
资源限额
一个docker host 会运行多个容器,每个容器都需要CPU、内存、IO资源。对于KVM和vmware等虚拟化技术,用户可以控制分配多少CPU、MEM资源给虚拟机。对于容器而言,Docker也提供了类似的机制避免某个容器因占用太多资源而影响其他容器乃至整个host的性能
内存限额
与操作系统类似,容器可以使用的内存包括两部分,物理内存和swap。docker通过下面两个参数来控制容器内存的使用量。
-m 或 --memory 设置内存的使用限额,比如 100M 2G
--memory-swap 设置内存+swap的使用限额
以上两个参数默认值为 -1 即不限制
如果只指定了 -m 200M 那么最多可以使用 200M内存 和 200M swap
docker run -it -m 200M --memory-swap=300M progrium/stress --vm 1 --vm-bytes 280M
分配200M 内存 和 300M swap
--vm 1 启动一个内存线程
--vm-bytes 280M 每个线程分配280M内存
progrium/stress 会不停的分配内存,释放内存
root@docker-lab:~# docker run -it -m 200M --memory-swap=300M progrium/stress --vm 1 --vm-bytes 280M
stress: info: [1] dispatching hogs: 0 cpu, 0 io, 1 vm, 0 hdd
stress: dbug: [1] using backoff sleep of 3000us
stress: dbug: [1] --> hogvm worker 1 [7] forked
stress: dbug: [7] allocating 293601280 bytes ...
stress: dbug: [7] touching bytes in strides of 4096 bytes ...
stress: dbug: [7] freed 293601280 bytes
stress: dbug: [7] allocating 293601280 bytes ...
stress: dbug: [7] touching bytes in strides of 4096 bytes ...
stress: dbug: [7] freed 293601280 bytes
stress: dbug: [7] allocating 293601280 bytes ...
stress: dbug: [7] touching bytes in strides of 4096 bytes ...
stress: dbug: [7] freed 293601280 bytes
root@docker-lab:~# docker run -it -m 200M progrium/stress --vm 1 --vm-bytes 410M # 内存不足,自动退出
stress: info: [1] dispatching hogs: 0 cpu, 0 io, 1 vm, 0 hdd
stress: dbug: [1] using backoff sleep of 3000us
stress: dbug: [1] --> hogvm worker 1 [8] forked
stress: dbug: [8] allocating 429916160 bytes ...
stress: dbug: [8] touching bytes in strides of 4096 bytes ...
stress: FAIL: [1] (416) <-- worker 8 got signal 9
stress: WARN: [1] (418) now reaping child worker processes
stress: FAIL: [1] (422) kill error: No such process
stress: FAIL: [1] (452) failed run completed in 1s
root@docker-lab:~# docker run -it -m 200M progrium/stress --vm 1 --vm-bytes 390M
stress: info: [1] dispatching hogs: 0 cpu, 0 io, 1 vm, 0 hdd
stress: dbug: [1] using backoff sleep of 3000us
stress: dbug: [1] --> hogvm worker 1 [7] forked
stress: dbug: [7] allocating 408944640 bytes ...
stress: dbug: [7] touching bytes in strides of 4096 bytes ...
stress: dbug: [7] freed 408944640 bytes
stress: dbug: [7] allocating 408944640 bytes ...
stress: dbug: [7] touching bytes in strides of 4096 bytes ...
stress: dbug: [7] freed 408944640 bytes