Docker Linux

How to check memory limit inside Docker container

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.


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 )

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 }' )

Leave a Reply

Your email address will not be published. Required fields are marked *