Nishant
Nishant

Reputation: 21934

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

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.

Upvotes: 1

Views: 1290

Answers (1)

larsks
larsks

Reputation: 312500

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.

Upvotes: 2

Related Questions