(七)限制容器對CPU的使用
? 默認設定下,所有容器可以平等地使用 host CPU 資源并且沒有限制,Docker 可以通過 -c 或 --cpu-shares 設定容器使用 CPU 的權重,如果不指定,默認值為 1024,
? 與記憶體限額不同,通過 -c 設定的 cpu share 并不是 CPU 資源的絕對數量,而是一個相對的權重值,某個容器最終能分配到的 CPU 資源取決于它的 cpu share 占所有容器 cpu share 總和的比例,換句話說:通過 cpu share 可以設定容器使用 CPU 的優先級,
? 比如在 host 中啟動了兩個容器:
docker run --name "container_A" -c 1024 ubuntu
docker run --name "container_B" -c 512 ubuntu
? container_A 的 cpu share 1024,是 container_B 的兩倍,當兩個容器都需要 CPU 資源時,container_A 可以得到的 CPU 是 container_B 的兩倍,
? 需要特別注意的是,這種按權重分配 CPU 只會發生在 CPU 資源緊張的情況下,如果 container_A 處于空閑狀態,這時,為了充分利用 CPU 資源,container_B 也可以分配到全部可用的 CPU,
下面我們繼續用 progrium/stress 做實驗,
①啟動 container_b,cpu share 為 1024:
root@cuiyongchao:~# docker run --name container_A -it -c 1024 progrium/stress:latest --cpu 1
stress: info: [1] dispatching hogs: 1 cpu, 0 io, 0 vm, 0 hdd
stress: dbug: [1] using backoff sleep of 3000us
stress: dbug: [1] --> hogcpu worker 1 [6] forked
? --cpu 用來設定作業執行緒的數量,因為當前 host 只有 1 顆 CPU,所以一個作業執行緒就能將 CPU 壓滿,如果 host 有多顆 CPU,則需要相應增加 --cpu 的數量,
②啟動container_c,cpu share 為512:
root@cuiyongchao:~# docker run --name container_B -it -c 512 progrium/stress:latest --cpu 1
stress: info: [1] dispatching hogs: 1 cpu, 0 io, 0 vm, 0 hdd
stress: dbug: [1] using backoff sleep of 3000us
stress: dbug: [1] --> hogcpu worker 1 [6] forked
③在 host 中執行 top,查看容器對 CPU 的使用情況
root@cuiyongchao:~# top
top - 12:21:37 up 8 days, 23:40, 8 users, load average: 1.91, 0.98, 0.41
Tasks: 217 total, 3 running, 125 sleeping, 0 stopped, 0 zombie
%Cpu(s): 50.1 us, 0.1 sy, 0.0 ni, 49.8 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem : 4015852 total, 1015488 free, 462096 used, 2538268 buff/cache
KiB Swap: 4015100 total, 4014024 free, 1076 used. 3278544 avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
④現在暫停 container_A:
root@cuiyongchao:~# docker pause container_A
container_A
⑤top 顯示 container_B 在 container_A 空閑的情況下能夠用滿整顆 CPU:
root@cuiyongchao:~# top
top - 12:28:47 up 8 days, 23:47, 8 users, load average: 4.89, 3.49, 1.69
Tasks: 221 total, 5 running, 123 sleeping, 0 stopped, 0 zombie
%Cpu(s): 99.9 us, 0.1 sy, 0.0 ni, 0.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem : 4015852 total, 1022156 free, 456852 used, 2536844 buff/cache
KiB Swap: 4015100 total, 4014024 free, 1076 used. 3286020 avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/213785.html
標籤:其他
