如何以root用户身份(最初)对其他非root用户容器执行某些操作? [英] How to execute something as a root user (initially) for an otherwise non-root user container?
问题描述
我想将主机的用户/组与docker机器同步,以使(开发人员)可以编辑容器内部或外部的文件.有这样的想法:使用Docker Volumes处理权限创建一个新用户.
I want to sync the host machine's user/group with the docker machine to enable (developers) to edit the files inside or outside the container. There are some ideas like this: Handling Permissions with Docker Volumes which creates a new user.
我想尝试类似的方法,但是我不想创建新用户,而是想使用 usermod
修改现有用户:
I would like to try a similar approach, but instead of creating a new user, I would like to modify the existing user using usermod
:
usermod -d /${tmp} docker # avoid `usermod` from modifying permissions automatically.
usermod -u "${HOST_USER_ID}" docker
groupmod -g "${HOST_GROUP_ID}" docker
usermod -d ${HOME} docker
这个想法似乎可行,但是当容器以docker用户(我想要的)运行时, usermod
抱怨此用户正在运行一个进程,因此无法更改用户ID".
This idea seems to work, but when the container is run as docker user (which is what I want), usermod
complains that "this user has a process running and so it can't change the user id".
如果添加 sudo
,它将更改用户ID,但是它将在下一个 sudo
中断,但将出现以下异常: sudo:unknown uid 1000:您是谁?
是避免上述问题的结果.
If add sudo
, it will change the user id, but it will break on the next sudo
will the following exception: sudo: unknown uid 1000: who are you?
as a consequence of side-stepping the above problem.
sudo usermod -d /${tmp} docker
sudo usermod -u "${HOST_USER_ID}" docker
sudo groupmod -g "${HOST_GROUP_ID}" docker # `sudo: unknown uid 1000: who are you?`
sudo usermod -d ${HOME} docker # `sudo: unknown uid 1000: who are you?`
在启动容器时是否可以以 root
身份运行某些内容,以及作为普通用户的启动脚本?似乎Dockerfile的 CMD
不执行两个命令;我也不能将多个命令组合为一个脚本,而我需要以两个用户身份运行-或者可以吗?我知道我可以创建其他图像,但是想知道是否还有更清洁的替代方法.
Is it possible to run something as a root
when the container is started, along with a bootstrap script as a normal user? It seems like the Dockerfile's CMD
doesn't executes two commands; nor can I club multiple commands into one script sine I need to run as two users - or can I? I know I can create a different image, but wondering if there are cleaner alternatives.
推荐答案
您可以以 root
身份启动容器,允许 ENTRYPOINT
脚本执行所需的任何更改,然后在执行容器 CMD
时切换到非特权用户.例如,使用 ENTRYPOINT
脚本,如下所示:
You can start your container as root
, allow the ENTRYPOINT
script to perform any changes you want, and then switch to an unprivileged user when you execute the container CMD
. E.g., use an ENTRYPOINT
script something like this:
#!/bin/sh
usermod -d /${tmp} docker
usermod -u "${HOST_USER_ID}" docker
groupmod -g "${HOST_GROUP_ID}" docker
exec runuser -u docker -- "$@"
如果没有 runuser
命令,则可以使用 su
获得类似的行为.
If you don't have the runuser
command, you can get similar behavior using su
.
这篇关于如何以root用户身份(最初)对其他非root用户容器执行某些操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!