Check mem_limit within a docker container

2019-02-05 09:30发布

After some crashes with a docker container with a too low mem_limit, how can i check in a container the mem_limit of this container? I want to print an error message on startup and exit if the mem_limit is set to low.

2条回答
等我变得足够好
2楼-- · 2019-02-05 09:58

The memory limit is enforced via cgroups. Therefore you need to use cgget to find out the memory limit of the given cgroup.

To test this you can run a container with a memory limit:

docker run --memory 512m --rm -it ubuntu bash

Run this within your container:

apt-get update
apt-get install cgroup-bin
cgget -n --values-only --variable memory.limit_in_bytes /
# will report 536870912

Docker 1.13 mounts the container's cgroup to /sys/fs/cgroup (this could change in future versions). You can check the limit using:

cat /sys/fs/cgroup/memory/memory.limit_in_bytes
查看更多
欢心
3楼-- · 2019-02-05 10:06

Worked for me in the container, thanks for the ideas Sebastian

#!/bin/sh
function memory_limit
{
  awk -F: '/^[0-9]+:memory:/ {
    filepath="/sys/fs/cgroup/memory"$3"/memory.limit_in_bytes";
    getline line < filepath;
    print line
  }' /proc/self/cgroup
}

if [[ $(memory_limit) < 419430400 ]]; then
  echo "Memory limit was set too small. Minimum 400m."
  exit 1
fi
查看更多
登录 后发表回答