How can a Docker container determine if its memory is limited?

I use cgget -n --values-only --variable memory.limit_in_bytes /Docker inside the container to find out how much memory it is allowed to use by docker run --memory=X. However, I need to know if memory was generally limited to which the command above did not respond, because it would just give me a large amount in this case ( 9223372036854771712in my tests).

So, is there a way to tell if memory is limited at all? I am looking for solutions that do not include launching in a docker runspecial way, for example, installing files from the host (for example, /var/...) or transferring an environment variable.

+4
source share
2 answers

, cgget. , cgget, , , , .

, , 100 , 2 , cgget 104857600, free 2098950144 bytes:

:

# free -b
             total       used       free     shared    buffers     cached
Mem:    2098950144  585707520 1513242624     712704   60579840  367644672
-/+ buffers/cache:  157483008 1941467136
Swap:   3137335296          0 3137335296    

, 100M

docker run --rm -it --memory=100M <any-image-with-cgget-available> bash -l

:

# free -b
             total       used       free     shared    buffers     cached
Mem:    2098950144  585707520 1513242624     712704   60579840  367644672
-/+ buffers/cache:  157483008 1941467136
Swap:   3137335296          0 3137335296    

# cgget -n --values-only --variable memory.limit_in_bytes /
104857600

, free docker, .

, bash script is_memory_limited, , , cgroup .

#!/bin/bash
set -eu

function is_memory_limited {
    type free >/dev/null 2>&1 || { echo >&2 "The 'free' command is not installed. Aborting."; exit 1; }
    type cgget >/dev/null 2>&1 || { echo >&2 "The 'cgget' command is not installed. Aborting."; exit 1; }
    type awk >/dev/null 2>&1 || { echo >&2 "The 'awk' command is not installed. Aborting."; exit 1; }

    local -ir PHYSICAL_MEM=$(free -m | awk 'NR==2{print$2}')
    local -ir CGROUP_MEM=$(cgget -n --values-only --variable memory.limit_in_bytes / | awk '{printf "%d", $1/1024/1024 }')

    if (($CGROUP_MEM <= $PHYSICAL_MEM)); then
        return 0
    else
        return 1
    fi
}


if is_memory_limited; then
    echo "memory is limited by cgroup"
else
    echo "memory is NOT limited by cgroup"
fi
+6

2 , , - , ,

docker container run --name mytestserver -m 200M -dt nginx

, 200M, ,

docker stats <container id>

CONTAINER ID        NAME                CPU %               MEM USAGE / LIMIT   MEM %               NET I/O             BLOCK I/O           PIDS
3afb4a8cfeb7        mytestserver        0.00%               **1.387MiB / 200MiB**   0.69%               8.48MB / 24.8kB     39.2MB / 8.25MB     2
0

Source: https://habr.com/ru/post/1622945/


All Articles