7

我在cgget -n --values-only --variable memory.limit_in_bytes /Docker 容器内使用,以查看允许使用多少内存docker run --memory=X9223372036854771712但是,我需要知道内存是否完全受到限制,上面的命令没有回答,因为在这种情况下(在我的测试中)它只会给我一个很大的数字。

那么,有什么方法可以判断内存是否是有限的呢?我正在寻找不涉及docker run以特殊方式运行的解决方案,例如从主机(例如,/var/...)挂载文件或传递环境变量。

4

2 回答 2

9

您可以将可用的总物理内存与cgget给您的数字进行比较。如果 给出的数字cgget低于总物理内存,那么您肯定知道 cgroups 用于限制内存的位置。

例如,如果我在具有 2G 物理内存的计算机上运行一个将内存限制为 100M 的容器,cgget104857600free命令报告2098950144字节时报告:

在码头主机上:

# free -b
             total       used       free     shared    buffers     cached
Mem:    2098950144  585707520 1513242624     712704   60579840  367644672
-/+ buffers/cache:  157483008 1941467136
Swap:   3137335296          0 3137335296    

启动一个限制为100M的容器

docker run --rm -it --memory=100M <any-image-with-cgget-available> bash -l

现在在该容器中:

# free -b
             total       used       free     shared    buffers     cached
Mem:    2098950144  585707520 1513242624     712704   60579840  367644672
-/+ buffers/cache:  157483008 1941467136
Swap:   3137335296          0 3137335296    

# cgget -n --values-only --variable memory.limit_in_bytes /
104857600

请注意,该free命令将在 docker 主机上报告与容器内相同的值。

最后,以下 bash 脚本定义了一个is_memory_limited可用于测试的函数,以检查 cgroup 是否用于限制内存。

#!/bin/bash
set -eu

function is_memory_limited {
    type free >/dev/null 2>&1 || { echo >&2 "The 'free' command is not installed. Aborting."; exit 1; }
    type cgget >/dev/null 2>&1 || { echo >&2 "The 'cgget' command is not installed. Aborting."; exit 1; }
    type awk >/dev/null 2>&1 || { echo >&2 "The 'awk' command is not installed. Aborting."; exit 1; }

    local -ir PHYSICAL_MEM=$(free -m | awk 'NR==2{print$2}')
    local -ir CGROUP_MEM=$(cgget -n --values-only --variable memory.limit_in_bytes / | awk '{printf "%d", $1/1024/1024 }')

    if (($CGROUP_MEM <= $PHYSICAL_MEM)); then
        return 0
    else
        return 1
    fi
}


if is_memory_limited; then
    echo "memory is limited by cgroup"
else
    echo "memory is NOT limited by cgroup"
fi
于 2016-01-06T00:10:21.527 回答
0

只需我的 2 美分,无需安装任何第三方工具,您只需使用 docker stats 检查有限的内存

docker container run --name mytestserver -m 200M -dt nginx

如本例,我将内存量限制为200M,现在来验证一下

docker stats <container id>

CONTAINER ID        NAME                CPU %               MEM USAGE / LIMIT   MEM %               NET I/O             BLOCK I/O           PIDS
3afb4a8cfeb7        mytestserver        0.00%               **1.387MiB / 200MiB**   0.69%               8.48MB / 24.8kB     39.2MB / 8.25MB     2
于 2019-10-08T05:26:53.360 回答