如何使Docker容器中的非root用户访问安装在主机上的卷 [英] How to give non-root user in Docker container access to a volume mounted on the host

查看:675
本文介绍了如何使Docker容器中的非root用户访问安装在主机上的卷的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以非root用户身份在Docker容器中运行我的应用程序。我这样做是因为它是最好的做法之一。但是,在运行容器时,我将主机卷挂载到 -v / some / folder:/ some / folder 。我这样做是因为在Docker容器内运行的应用程序需要将文件写入挂载的主机文件夹。但是,由于我以非root用户身份运行我的应用程序,因此无权写入该文件夹。



问题



是否可以给Docker容器中的非root用户授予对托管卷的访问权限?



如果不是,是我在Docker容器中以root身份运行进程的唯一选择?

解决方案

这里没有魔术解决方案:Docker中的权限被管理与没有码头的许可一样。您需要运行相应的 chown chmod 命令来更改目录的权限。



一个解决方案是让您的容器以root用户身份运行,并使用 ENTRYPOINT 脚本进行适当的权限更改,然后使用 CMD 作为非特权用户。例如,将以下内容放在 entrypoint.sh 中:

 #! / bin / sh 

chown -R appuser:appgroup / path / to / volume
exec runuser -u appuser$ @
pre>

这假设您有可用的 runuser 命令。您可以使用 sudo 完成相同的事情。



使用上述脚本包含一个 ENTRYPOINT 指令在您的Dockerfile中:

  FROM baseimage 

COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT [/ bin / sh,entrypoint.sh]
CMD [/ usr / bin / myapp]

这将启动容器:

  / bin / sh entrypoint.sh / usr / bin / myapp 

entrypoint脚本将使所需权限更改,然后运行 / usr / bin / myapp 作为 appuser


I am running my application in a Docker container as a non-root user. I did this since it is one of the best practices. However, while running the container I mount a host volume to it -v /some/folder:/some/folder . I am doing this because my application running inside the docker container needs to write files to the mounted host folder. But since I am running my application as a non-root user, it doesn't have permission to write to that folder

Question

Is it possible to give a nonroot user in a docker container access to the hosted volume?

If not, is my only option to run the process in docker container as root?

解决方案

There's no magic solution here: permissions inside docker are managed the same as permissions without docker. You need to run the appropriate chown and chmod commands to change the permissions of the directory.

One solution is to have your container run as root and use an ENTRYPOINT script to make the appropriate permission changes, and then your CMD as an unprivileged user. For example, put the following in entrypoint.sh:

#!/bin/sh

chown -R appuser:appgroup /path/to/volume
exec runuser -u appuser "$@"

This assumes you have the runuser command available. You can accomplish pretty much the same thing using sudo instead.

Use the above script by including an ENTRYPOINT directive in your Dockerfile:

FROM baseimage

COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/bin/sh", "entrypoint.sh"]
CMD ["/usr/bin/myapp"]

This will start the container with:

/bin/sh entrypoint.sh /usr/bin/myapp

The entrypoint script will make the required permissions changes, then run /usr/bin/myapp as appuser.

这篇关于如何使Docker容器中的非root用户访问安装在主机上的卷的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆