如何正确报告 docker 容器内的可用 RAM?

Ant*_*ong 2 python python-2.7 docker

我已经完成了以下测试,我发现我无法psutil用来检索有意义的数据。

基本上我试图运行这个命令来使用 python 报告容器内的可用内存。

我已经运行了 3 次测试,每次都使用不同的内存参数:

以下是测试:

docker run -m 10000000  -ti python:2.7  bash  
docker run -m 100000000  -ti python:2.7  bash  
docker run -m 800000000  -ti python:2.7  bash   
Run Code Online (Sandbox Code Playgroud)

这是结果

> docker run -m 10000000  -ti python:2.7  bash                                                                                                     
root@310de7b416cc:/# pip install psutil && python -c "import psutil; print psutil.virtual_memory().available"
Killed

> docker run -m 100000000  -ti python:2.7  bash                                                                                                    
root@e7aade23c143:/# pip install psutil && python -c "import psutil; print psutil.virtual_memory().available"
Collecting psutil
  Downloading psutil-5.3.1.tar.gz (397kB)
    100% |????????????????????????????????| 399kB 2.8MB/s 
Building wheels for collected packages: psutil
  Running setup.py bdist_wheel for psutil ... done
  Stored in directory: /root/.cache/pip/wheels/bc/00/68/b4cbf1017e55880ef2afd1a248a1c88311f38a574c8929d687
Successfully built psutil
Installing collected packages: psutil
Successfully installed psutil-5.3.1
1741164544

> docker run -m 800000000  -ti python:2.7  bash                                                                                                   
root@b8a28ad93432:/# pip install psutil && python -c "import psutil; print psutil.virtual_memory().available"
Collecting psutil
  Downloading psutil-5.3.1.tar.gz (397kB)
    100% |????????????????????????????????| 399kB 2.8MB/s 
Building wheels for collected packages: psutil
  Running setup.py bdist_wheel for psutil ... done
  Stored in directory: /root/.cache/pip/wheels/bc/00/68/b4cbf1017e55880ef2afd1a248a1c88311f38a574c8929d687
Successfully built psutil
Installing collected packages: psutil
Successfully installed psutil-5.3.1
1739603968
Run Code Online (Sandbox Code Playgroud)

在第一次测试中,工作立即被杀死。由于 RAM 分配不足,这是意料之中的。

但是在第二次和第三次测试中,即使-m参数相差 8 倍,python 代码返回的结果大致相同:1741164544 和 1739603968(即 1,741,164,544 和 1,739,603,968)

为什么会这样?

我的主机是 mac,它有 16G RAM。

mya*_*aut 6

Docker 使用CGroups来控制容器对资源的使用,因此您应该检查 CGroup 文件:

$ docker run -m 800000000  -ti centos  bash   
[root@c7406a25bc4b /]# cat /sys/fs/cgroup/memory/memory.limit_in_bytes
799997952
Run Code Online (Sandbox Code Playgroud)

psutil很可能使用/proc/meminfo显示系统而不是容器功能的文件。

另见:https : //serverfault.com/questions/680963/lxc-container-shows-hosts-full-ram-amount-and-cpu-count