PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 18, 2022

[FIXED] How to get containter memory limit in Python?

 October 18, 2022     docker, get, limit, memory, python     No comments   

Issue

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


Answered By - atline
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing