Docker user namespacing and sudo

dockersudo

I am trying to get a Docker container working with using the user namespacing feature and sudo. If I create the container with the -u flag set to a random UID, then sudo doesn't work, and you get this message:

sudo: unknown uid 1234: who are you?

The user is clearly not in the /etc/passwd, which is causing a problem for sudo. I'm trying to get this image to work with OpenShift's default settings, which are to generate a random UID, which is part of the root group (0), but I need to run commands as a fixed user later, so want to use sudo to do that (and tightly control which commands can be run). It does seem to work if I append an entry to /etc/passwd, but that seems ugly, as it would need to be run at every container start-up (as /etc/passwd isn't in a volume).

Does anyone have any other suggestions?

Edit: note that OpenShift generates a different random UID every time a container is run.

Best Answer

My apologies, I am not familiar with OpenShift, but in a vanilla Docker environment I would suggest you create a new image based off a modified container that has the changes you want, then run all new containers from that image. You can pretty easily create another image based on the one you are currently using which has your modified /etc/passwd as well as any other tight controls you want to impose.

For example (I'm using ubuntu:latest since you didn't mention the actual image you are trying to run from). First, run a new container based on the image of choice and execute just one command to create a new user and add to the sudo group:

$ docker run --name test ubuntu:latest useradd -u 1234 -G sudo newuser

Now, create a new image based off the modified image in the new container:

$ docker commit test test-image
<image id>

Now you have a new image called "test-image" you can run new containers from. Run a new container based on that image to see if the new user is in /etc/passwd:

$ docker run --name test2 --rm test-image cat /etc/passwd | grep 1234
newuser:x:1234:1234::/home/newuser:

From now on every image based off of "test-image" will have 'newuser' as a valid user, already in the /etc/passwd file and part of the group sudo.

If you want to do more detailed customization, use the following instead to run your initial container, and when you are happy exit and commit as shown above:

$ docker run --name test -it ubuntu:latest 

Note that simply adding the user to the sudo group may not be sufficient to let it run commands as root. Run 'visudo' and modify as appropriate. The example image above from ubuntu needs to have the sudo package and an editor installed before it will allow sudo'ing.