如何使Docker容器中的非root用户访问安装在主机上的卷 [英] How to give non-root user in Docker container access to a volume mounted on the host
问题描述
我以非root用户身份在Docker容器中运行我的应用程序。我这样做是因为它是最好的做法之一。但是,在运行容器时,我将主机卷挂载到 -v / some / folder:/ some / folder
。我这样做是因为在Docker容器内运行的应用程序需要将文件写入挂载的主机文件夹。但是,由于我以非root用户身份运行我的应用程序,因此无权写入该文件夹。
问题
是否可以给Docker容器中的非root用户授予对托管卷的访问权限?
如果不是,是我在Docker容器中以root身份运行进程的唯一选择?
这里没有魔术解决方案:Docker中的权限被管理与没有码头的许可一样。您需要运行相应的 chown
和 chmod
命令来更改目录的权限。
一个解决方案是让您的容器以root用户身份运行,并使用 ENTRYPOINT
脚本进行适当的权限更改,然后使用 CMD
作为非特权用户。例如,将以下内容放在 entrypoint.sh
中:
#! / bin / sh
pre>
chown -R appuser:appgroup / path / to / volume
exec runuser -u appuser$ @
这假设您有可用的
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 folderQuestion
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
andchmod
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 yourCMD
as an unprivileged user. For example, put the following inentrypoint.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 usingsudo
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
asappuser
.这篇关于如何使Docker容器中的非root用户访问安装在主机上的卷的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!