https://blog.csdn.net/twx843571091/article/details/113635187

一开始以为使用 free -h 得到的就是docker 容器本身的内存使用情况

容器
root@feb0423bbe52:/sys/fs/cgroup/memory# free -h
total used free shared buff/cache available
Mem: 62G 21G 267M 423M 41G 40G
Swap: 5.0G 834M 4.2G
1
2
3
4
5
看到这个结果产生了疑问,因为和宿主机一模一样啊!

宿主机
[root@mh-server-22 ~]# free -h
total used free shared buff/cache available
Mem: 62G 19G 1.2G 337M 41G 42G
Swap: 5.0G 835M 4.2G

1
2
3
4
5
6
网上查到说,可以使用 docker stats —no-stream 查看容器内存、CPU使用情况,可以是可以,但是还是不够详细(可能大多数人在这一步就OK了,也没必要往下看了)

我需要知道docker容器自己使用了多少cache memory以及更多信息。

经过各种Google,找到这篇文章 Getting memory usage in Linux and Docker,他也提到在容器里使用 free -h 和在宿主机使用 free -h 是一样的,free -h 本质上是读取 /proc/meminfo 文件内容。

文章中简单的介绍了下Docker背后隔离原理:

According to Docker Overview: The Underlying Technology, processes in a Docker container directly run in their host OS without any virtualization, but they are isolated from the host OS and other containers in effect thanks to these Linux kernel features:

namespaces: Isolate PIDs, hostnames, user IDs, network accesses, IPC, etc.
cgroups: Limit resource usage
UnionFS: Isolate file system
Because of the namespaces, ps command lists processes of Docker containers in addition to other processes in the host OS, while it cannot list processes of host OS or other containers in a docker container.

By default, Docker containers have no resource constraints. So, if you run one container in a host and don’t limit resource usage of the container, and this is my case, the container’s “free memory” is same as the host OS’s “free memory”.

核心意思是 资源不隔离。所以 the container’s “free memory” is same as the host OS’s “free memory”.

然而要怎么样才能获取到容器本身的资源信息呢?

进入容器的 /sys/fs/cgroup/memory 这个目录

里面有关内存的一些信息。如下:

root@feb0423bbe52:/sys/fs/cgroup/memory# ls
cgroup.clone_children memory.force_empty memory.kmem.slabinfo memory.kmem.tcp.usage_in_bytes memory.memsw.failcnt memory.move_charge_at_immigrate memory.soft_limit_in_bytes memory.use_hierarchy
cgroup.event_control memory.kmem.failcnt memory.kmem.tcp.failcnt memory.kmem.usage_in_bytes memory.memsw.limit_in_bytes memory.numa_stat memory.stat notify_on_release
cgroup.procs memory.kmem.limit_in_bytes memory.kmem.tcp.limit_in_bytes memory.limit_in_bytes memory.memsw.max_usage_in_bytes memory.oom_control memory.swappiness tasks
memory.failcnt memory.kmem.max_usage_in_bytes memory.kmem.tcp.max_usage_in_bytes memory.max_usage_in_bytes memory.memsw.usage_in_bytes memory.pressure_level memory.usage_in_bytes
root@feb0423bbe52:/sys/fs/cgroup/memory#
1
2
3
4
5
6
查看 memory.stat 文件内容,可以得到很多信息,包括我需要的cache memory:

total_cache 1579098112 : 缓存内存
total_rss 497885184:已使用内存
附注:memory.stat 每项含义请看这篇文章https://xuxinkun.github.io/2016/05/16/memory-monitor-with-cgroup/

其实portainer.io对容器的统计图表也是读取的memory.stat 文件: