You should know the memory limit of your container (not the whole host) when packing applications there. For example and simplicity, let’s imagine you are creating customized redis, memcached or varnish image and you wish to know available memory when the container starts to set it as the memory limit for your application.
There are two options for it, you can choose one depending on cgroup version (v1 or v2), or check both.
/sys/fs/cgroup/memory/memory.limit_in_bytes
/sys/fs/cgroup/memory.max
So, here is the bash code snippet:
if [ -f "/sys/fs/cgroup/memory/memory.limit_in_bytes" ]; then
container_memory_limit=$( cat /sys/fs/cgroup/memory/memory.limit_in_bytes )
elif [ -f "/sys/fs/cgroup/memory.max" ]; then
container_memory_limit=$( cat /sys/fs/cgroup/memory.max )
fi
There in variable container_memory_limit will be a memory limit in bytes. Just in case you can also cast the result value to an integer using AWK (i like it):
container_memory_limit=$( awk -v memory_limit=$container_memory_limit 'BEGIN { printf "%0.0f\n", memory_limit }' )