Search code examples
pythondockermemorygetlimit

How to get containter memory limit in Python?


I'm trying to retrieve the real memory limit set to a Docker container within it using Python:

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))"

but it returns all available memory from the host machine.

I know I could use Docker package for Python and bind-mount /var/run/docker.sock to get that info from inspecting container configuration, but I need to know if there is another way because I can't use that method.


Solution

  • Container's memory limit is controlled by linux cgroups, so you could fetch the value of /sys/fs/cgroup/memory/memory.limit_in_bytes in container to caculate the limit memory within container:

    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
    >>>