1 启动容器时限制容器内存
docker run -m 4g --memory-swap -1
2限制已启动容器的内存
docker stop containerId
docker update containerId -m 4g --memory-swap -1
docker start containerId
3命令详解
--memory 或 -m 限制容器的内存使用量(如10m,200m等)
--memory-swap # 限制内存和 Swap 的总和,不设置的话默认为--memory的两倍
如果只指定了 --memory 则 --memory-swap 默认为 --memory 的两倍
如果 --memory-swap 和 --memory 设置了相同值,则表示不使用 Swap
如果 --memory-swap 设置为 -1 则表示不对容器使用的 Swap 进行限制
如果设置了 --memory-swap 参数,则必须设置 --memory 参数
后期 update --memory 时数值不能超过 --memory-swap 的值,否则会报错 Memory limit should be smaller than already set memoryswap limit
4查询是否配置成功
docker inspect containerId
5错误情况
错误场景一
Your kernel does not support swap limit capabilities or the cgroup is not mounted
解决
// 1 打开/etc/default/grub文件
sudo vi /etc/default/grub
// 2 加入下面配置
GRUB_CMDLINE_LINUX="cgroup_enable=memory swapaccount=1"
// 3 更新grub系统
sudo update-grub
// 4 重启
错误场景二
Memory limit should be smaller than already set memoryswap limit, update the memoryswap at the same time
解决
ocker 默认没有启用memory-swap交换内存,直接设置了内存问题会出问题,也就是说宿主 swap 支持使用多少则容器即可使用多少
设置内存的同时必须设置–memory-swap