Docker cpu memory quota使用说明

来源:互联网 发布:网络舆情工作计划 编辑:程序博客网 时间:2024/06/05 14:35

1.Docker内存限制

1.0 测试工具

     stress

1.1 内存限制选项

  • -m--memory=""
    • Memory limit (format: <number>[<unit>]). Number is a positive integer. Unit can be one of bkm, or g. Minimum is 4M.
  • --memory-swap=""
    • Total memory limit (memory + swap, format: <number>[<unit>]). Number is a positive integer. Unit can be one of bkm, or g.

 

1.2 示例

docker run -it --rm -m 100M --memory-swap -1 ubuntu-stress:latest /bin/bash

    指定限制内存大小并且设置 memory-swap 值为 -1,表示容器程序使用内存受限,而 swap 空间使用不受限制(宿主 swap 支持使用多少则容器即可使用多少。如果 --memory-swap 设置小于 --memory则设置不生效,使用默认设置)。

docker run -it --rm -m 100M ubuntu-stress:latest /bin/bash

    如果不添加--memory-swap选项,则表示容器中程序可以使用100M内存和100Mswap内存,默认情况下,--memory-swap 会被设置成 memory 的 2倍。-m 为物理内存上限,而 --memory-swap 则是 memory + swap 之和,当压测值是 --memory-swap 上限时,则容器中的进程会被直接 OOM kill。

 

例如运行容器 

docker run -it -m 100M --memory-swap 400M ubuntu-stress:latest /bin/bash  压测几秒钟后超出内存限制kill掉进程

root@5ed1fd88a1aa:/# stress --vm 1 --vm-bytes 400M # 压测到 400M 程序会被 kill 

stress: info: [24] dispatching hogs: 0 cpu, 0 io, 1 vm, 0 hdd 

 

stress: FAIL: [24] (416) <-- worker 25 got signal 

stress: WARN: [24] (418) now reaping child worker processes

 stress: FAIL: [24] (452) failed run completed in 3s

 

  如果在k8s中对容器限制内存,那么在运行时,pod内的容器超出限制后会自动重启。



2 CPU限制参数

目前 Docker 支持 CPU 资源限制选项

  • -c--cpu-shares=0
    • CPU shares (relative weight)
    • -c 选项将会废弃,推荐使用 --cpu-shares
  • --cpu-period=0
    • Limit the CPU CFS (Completely Fair Scheduler) period
  • --cpu-quota=0
    • Limit the CPU CFS (Completely Fair Scheduler) quota

2.1 -c or --cpu-shares参数的使用

    默认所有的容器对于 CPU 的利用占比都是一样的,-c 或者 --cpu-shares 可以设置 CPU 利用率权重,默认为 1024,可以设置权重为 2 或者更高(单个 CPU 为 1024,两个为 2048,以此类推)。如果设置选项为 0,则系统会忽略该选项并且使用默认值 1024。通过以上设置,只会在 CPU 密集(繁忙)型运行进程时体现出来。当一个 container 空闲时,其它容器都是可以占用 CPU 的。cpu-shares 值为一个相对值,实际 CPU 利用率则取决于系统上运行容器的数量。

    假如一个 1core 的主机运行 3 个 container,其中一个 cpu-shares 设置为 1024,而其它 cpu-shares 被设置成 512。当 3 个容器中的进程尝试使用 100% CPU 的时候「尝试使用 100% CPU 很重要,此时才可以体现设置值」,则设置 1024 的容器会占用 50% 的 CPU 时间。如果又添加一个 cpu-shares 为 1024 的 container,那么两个设置为 1024 的容器 CPU 利用占比为 33%,而另外两个则为 16.5%。简单的算法就是,所有设置的值相加,每个容器的占比就是 CPU 的利用率,如果只有一个容器,那么此时它无论设置 512 或者 1024,CPU 利用率都将是 100%。当然,如果主机是 3core,运行 3 个容器,两个 cpu-shares 设置为 512,一个设置为 1024,则此时每个 container 都能占用其中一个 CPU 为 100%。

2.2 --cpu-period & --cpu-quota

   这两个选项是1.7版本出现的。

    --cpu-period是用来指定容器对CPU的使用要在多长时间内做一次重新分配,而--cpu-quota是用来指定在这个周期内,最多可以有多少时间用来跑这个容器。跟--cpu-shares不同的是这种配置是指定一个绝对值,而且没有弹性在里面,容器对CPU资源的使用绝对不会超过配置的值。

比如说A容器配置的--cpu-period=100000 --cpu-quota=50000,那么A容器就可以最多使用50%个CPU资源,如果配置的--cpu-quota=200000,那就可以使用200%个CPU资源。

0 0