Docker实用贴士—容器内存识别问题
情形再现
大家使用docker下容器时,是否遇到过下面几种情况:
创建的容器运行一段时间后重启,查看日志发现被kill后由于自动启动而重启(如甜糖)
创建的容器明明显示内存充足,可是却因为内存不足而运行错误(如基于selenium的项目)
容器将内存作为缓存交换区,本应该分配多少占用多少,但是分配了2G却跑满了16G
原因分析
这些情况背后的原因是大家弄错了创建容器时设置的内存的概念。我们一般在创建时使用-m命令来设置内存,但我们看一下官方doc对于-m的说明:
Limit a container’s access to memory
Docker can enforce hard memory limits, which allow the container to use no more than a given amount of user or system memory, or soft limits, which allow the container to use as much memory as it needs unless certain conditions are met, such as when the kernel detects low memory or contention on the host machine. Some of these options have different effects when used alone or when more than one option is set.-m or --memory=The maximum amount of memory the container can use. If you set this option, the minimum allowed value is 6m (6 megabytes). That is, you must set the value to at least 6 megabytes.
翻译一下就是,我们所设置的是限制内存,用来防止容器占用过多内存。就像是你给小狗栓了一根绳子,你只能限制他不跑远,但方式是一跑远就被勒脖子。而真正的方式应该是让容器看到限制的内存,从而自行调节。
解决方法
说了那么多,我们该如何解决呢?用lxcfs把docker设定的限制内存映射给容器。我们以ubuntu举例说明
第一步:安装lxcfs
运行如下命令
apt install lxcfs -y
成功后会显示successfully,由于我已经安装了,显示的是已存在
安装lxcfs
第二步:重新安装原先容器
这里顺便说一下如何升级容器。docker与容器是一种映射关系,容器所使用的配置文件、存放的数据文件等通过映射的位置放到宿主机上。所以升级容器也好、删除容器也好,只要你映射的文件夹没有删除,并且重装时映射位置没有变化,那么所有的数据理论上是不变的。所以升级容器就是简单地删除重装。不过如果你使用portainer,可以在如图的位置选择一键重建。
点击重建
选择拉取最新
回归正题,明白了前面说的,就可以放心大胆的删除容器重装了。注意,删除后重新安装时,要添加如下的映射关系:
-v /var/lib/lxcfs/proc/meminfo:/proc/meminfo:rw
例如,你要拉取安装甜糖镜像,官方给的命令如下:(表示换行符,原本应该一行打出来的命令,通过来换行变的美观,同时保证一次运行)
sudo docker run -d
-v /mnt/host/dir:/mnt/data/ttnode
-v /var/run/docker.sock:/var/run/docker.sock
--name ttnode
--hostname ttnode
--net=host
--restart=always
--memory=2g
--cpus=1.5
tiptime/ttnode:latest
现在你重建的命令如下
sudo docker run -d
-v /mnt/host/dir:/mnt/data/ttnode
-v /var/lib/lxcfs/proc/meminfo:/proc/meminfo:rw
-v /var/run/docker.sock:/var/run/docker.sock
--name ttnode
--hostname ttnode
--net=host
--restart=always
--memory=2g
--cpus=1.5
tiptime/ttnode:latest
加粗的部分就是添加的新的映射关系。无论哪个镜像,都是如此添加一句。
最后:检查效果
输入如下命令查看一下各个容器情况
docker stats -a
查看状态
可以看到,我设定的limit为2.8g,而甜糖设定是占用识别到的内存的80%,因此设定内存已经成功映射给容器了。
总结
至此,我们已经完成了内存设定。如果想看更多docker相关内容,欢迎大家留言。
本人学疏才浅,文章如有错误还请大家多多指正。
作者声明本文无利益相关,欢迎值友理性交流,和谐讨论~
cosz
校验提示文案
IP_man
校验提示文案
POKO哑虎呸呸
校验提示文案
POKO哑虎呸呸
校验提示文案
IP_man
校验提示文案
cosz
校验提示文案