docker 遇到swapon failed Operation not permitted

在安装phalcon的时候遇到内存不足的问题,需要swap增加内存,可是在docker里面遇到

1
swapon failed: Operation not permitted

该问提百思不得其姐,最后在docker官网找到了解释,最后说一下,搜索还是google靠谱

Hi,
As each running docker container uses the host Kernel, they also use the memory and swap of the host. If this is a one of requirement its better to increase the host swap space.
If you want to still add swap from the container you have two options.
Run container in privileged mode
In this case you will have to run the container with –privileged option.

Example

docker run -it –rm –privileged centos:6
Running container with privileged mode gives container full privilege on the host. If you read the manpage of swapon you can see that for swapon to run the process should have CAP_SYS_ADMIN capability. In Docker you can add a particular capability selectively to the container using the –cap-add argument.

Example

docker run -it –rm –cap-add SYS_ADMIN centos:6
If you run the container in either of the above two modes you can achieve what you are trying.
Now the problem with this approach is , when you create swap inside the container and start using that, its actually the Host Kernel that is using it, as a result when you exit the container without a swapoff the host kernel will be still using the file, and you wont get a clean exit of the container. You will see a dead status for the container.

嗨,
由于每个运行的docker容器都使用主机内核,它们还使用主机的内存和交换。如果这是要求更好的增加主机交换空间的一个。
如果你想从容器中添加交换,你有两个选择。
以特权模式运行容器
在这种情况下,您将必须使用–privileged选项运行容器。
#示例
docker run -it –rm –privileged centos:6
运行具有特权模式的容器可以为主机提供容器完整权限。如果您阅读swapon的联机帮助页面,您可以看到,对于swapon来运行该进程应该具有CAP_SYS_ADMIN功能。在Docker中,您可以使用-cap-add参数有选择地向容器添加特定的功能。
#示例
docker run -it –rm –cap-add SYS_ADMIN centos:6
如果您以上述两种模式运行容器,您可以实现您正在尝试的功能。
现在,这种方法的问题是,当您在容器内创建交换并开始使用它时,实际上是使用它的主机内核,因此当您退出容器而不进行swapoff时,主机内核将仍然使用该文件,你不会得到一个干净的出口的容器。您将看到容器的死亡状态。