How to execute something as a root user (initially) for an otherwise non-root user container?

可紊 提交于 2021-02-11 08:14:42

问题


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.

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

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".

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?`

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.


回答1:


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 -- "$@"

If you don't have the runuser command, you can get similar behavior using su.



来源:https://stackoverflow.com/questions/61366559/how-to-execute-something-as-a-root-user-initially-for-an-otherwise-non-root-us

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!