如何正确报告docker集装箱内的可用RAM?

我做了以下testing,发现我不能使用psutil来检索有意义的数据。

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

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

这里是testing:

 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 

这是结果

 > 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 

在第一次testing中,这个工作马上被杀死了。 由于内存分配不足,这是预期的。

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

为什么是这样?

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

Docker使用CGroups来控制容器的资源使用情况,所以你应该检查CGroup文件:

 $ docker run -m 800000000 -ti centos bash [root@c7406a25bc4b /]# cat /sys/fs/cgroup/memory/memory.limit_in_bytes 799997952 

psutil很可能使用/proc/meminfo文件来显示系统的容器function。

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