(六)限制容器對記憶體的使用
? 一個 docker host 上會運行若干容器,每個容器都需要 CPU、記憶體和 IO 資源,對于 KVM,VMware 等虛擬化技術,用戶可以控制分配多少 CPU、記憶體資源給每個虛擬機,對于容器,Docker 也提供了類似的機制避免某個容器因占用太多資源而影響其他容器乃至整個 host 的性能,
(1)記憶體限額
? 與作業系統類似,容器可使用的記憶體包括兩部分:物理記憶體和 swap, Docker 通過下面兩組引數來控制容器記憶體的使用量,
-m或--memory:設定記憶體的使用限額,例如 100M, 2G,--memory-swap:設定 記憶體+swap 的使用限額,
root@cuiyongchao:/dockerfile# docker run --memory=200M --memory-swap=300M ubuntu
? 其含義是允許該容器最多使用 200M 的記憶體和 100M 的 swap,默認情況下,上面兩組引數為 -1,即對容器記憶體和 swap 的使用沒有限制,
? 下面我們將使用 progrium/stress 鏡像來學習如何為容器分配記憶體,該鏡像可用于對容器執行壓力測驗,執行如下命令:
docker run -it -m 200M --memory-swap=300M progrium/stress --vm 1 --vm-bytes 280M
--vm 1:啟動 1 個記憶體作業執行緒,
--vm-bytes 280M:每個執行緒分配 280M 記憶體,
運行結果如下:
root@cuiyongchao:/dockerfile# docker run -it -m 200M --memory-swap=300M progrium/stress --vm 1 --vm-bytes 280M
Unable to find image 'progrium/stress:latest' locally
latest: Pulling from progrium/stress
Image docker.io/progrium/stress:latest uses outdated schema1 manifest format. Please upgrade to a schema2 image for better future compatibility. More information at https://docs.docker.com/registry/spec/deprecated-schema-v1/
a3ed95caeb02: Pull complete
871c32dbbb53: Pull complete
dbe7819a64dd: Pull complete
d14088925c6e: Pull complete
58026d51efe4: Pull complete
7d04a4fe1405: Pull complete
1775fca35fb6: Pull complete
5c319e267908: Pull complete
Digest: sha256:e34d56d60f5caae79333cee395aae93b74791d50e3841986420d23c2ee4697bf
Status: Downloaded newer image for progrium/stress:latest
WARNING: Your kernel does not support swap limit capabilities or the cgroup is not mounted. Memory limited without swap.
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 [6] forked
stress: dbug: [6] allocating 293601280 bytes ...
stress: dbug: [6] touching bytes in strides of 4096 bytes ...
stress: dbug: [6] freed 293601280 bytes
stress: dbug: [6] allocating 293601280 bytes ...
stress: dbug: [6] touching bytes in strides of 4096 bytes ...
stress: dbug: [6] freed 293601280 bytes
stress: dbug: [6] allocating 293601280 bytes ...
stress: dbug: [6] touching bytes in strides of 4096 bytes ...
stress: dbug: [6] freed 293601280 bytes
stress: dbug: [6] allocating 293601280 bytes ...
stress: dbug: [6] touching bytes in strides of 4096 bytes ...
stress: dbug: [6] freed 293601280 bytes
stress: dbug: [6] allocating 293601280 bytes ...
stress: dbug: [6] touching bytes in strides of 4096 bytes ...
因為 280M 在可分配的范圍(300M)內,所以作業執行緒能夠正常作業,其程序是:
- 分配 280M 記憶體,
- 釋放 280M 記憶體,
- 再分配 280M 記憶體,
- 再釋放 280M 記憶體,
- 一直回圈......
如果讓作業執行緒分配的記憶體超過 300M,結果如下:
root@cuiyongchao:/dockerfile# docker run -it -m 200M --memory-swap=300M progrium/stress --vm 1 --vm-bytes 310M
分配的記憶體超過限額,stress 執行緒報錯,容器退出,
如果在啟動容器時只指定 -m 而不指定 --memory-swap,那么 --memory-swap 默認為 -m 的兩倍,比如:
docker run -it -m 200M ubuntu
容器最多使用 200M 物理記憶體和 200M swap,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/213219.html
標籤:其他
