Home > Software design >  What is the real memory available in Docker container?
What is the real memory available in Docker container?

Time:05-11

I've run mongodb service via docker-compose like this:

version: '2'
services:
  mongo:
    image: mongo
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example
    mem_limit: 4GB

If I run docker stats I can see 4 GB allocated:

CONTAINER ID   NAME                     CPU %     MEM USAGE / LIMIT     MEM %     NET I/O           BLOCK I/O    PIDS
cf3ccbd17464   michal_mongo_1           0.64%     165.2MiB / 4GiB       4.03%     10.9kB / 4.35kB   0B / 483kB   35

But I run this command I get RAM from my laptop which is 32 GB:

~$ docker exec michal_mongo_1 free -g
              total        used        free      shared  buff/cache   available
Mem:             31           4          17           0           9          24
Swap:             1           0           1

How does mem_limit affect the memory size then?

CodePudding user response:

free (and other utilities like top) will not report correct numbers inside a memory-constraint container because it gathers its information from /proc/meminfo which is not namespaced.

If you want the actual limit, you must use the entries populated by cgroup pseudo-filesystem under /sys/fs/cgroup.

For example:

docker run --rm -i --memory=128m busybox cat /sys/fs/cgroup/memory/memory.limit_in_bytes

The real-time usage information is available under /sys/fs/cgroup/memory/memory.stat.

You will probably need the resident-set-size (rss), for example (inside the container):

grep -E -e '^rss\s ' /sys/fs/cgroup/memory/memory.stat

For a more in-depth explanation, see also this article

  • Related