我正在尝试使用 Python 检索为其中的 Docker 容器设置的实际内存限制:
docker run --rm -it --memory="2g"python:3.8 python -c "import os; print((os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES') )/(1024.**3))"
但它返回主机的所有可用内存。
我知道我可以使用 Python 的 Docker 包并绑定(bind)安装 /var/run/docker.sock
从检查容器配置中获取该信息,但我需要知道是否还有其他方法因为我无法使用该方法。
最佳答案
容器的内存限制是由linux cgroups控制的,因此您可以通过获取容器中的/sys/fs/cgroup/memory/memory.limit_in_bytes
的值来计算容器内的限制内存:
root@pie:~# docker run --rm -it --memory="2g" python:3.8 /bin/bash
root@e22c4275f26c:/# python3
Python 3.8.15 (default, Oct 14 2022, 00:19:58)
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> limit_in_bytes=subprocess.check_output(["cat", "/sys/fs/cgroup/memory/memory.limit_in_bytes"]).decode("utf-8")
>>> print(int(limit_in_bytes)/(1024**3))
2.0
>>>
关于python - 如何在Python中获取容器内存限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74052985/