4

Running a docker image with a command line such as:

> docker run -it -v $OutsideDir:$InsideDir -u $(id -u):$(id -g) c0ffeebaba bash

I am able to work on my data as the current user on the host from inside the docker container. However, asking inside the container 'whoami' gives the response that the UID is unknown.

So the shell is executed on a user without a home-directory. How can I get some initialization being done for that user? Is there a way to map the user id and group id of an external user to a specific user name from inside? Can this be done dynamically, so that it would work for any user, specified through the '--user' flag as shown above?

My first approach would have been to use 'CMD' in the Dockerfile such as

CMD ["source", "/home/the_user/.bashrc" ]

But, that does not work.

Frank-Rene Schäfer
  • 3,182
  • 27
  • 51

1 Answers1

3

A relatively simple solution would be to wrap the docker run in a script, mapping in the /etc/passwd and /etc/group files from the host onto the container, as well as the user's home directory, so something like:

#!/bin/bash -p

# command starts with mapping passwd and group files
cmd=(docker run -v /etc/passwd:/etc/passwd:ro -v /etc/group:/etc/group:ro)
# add home directory:
myhome=$(getent passwd $(id -nu) | awk -F: '{print $6}')
cmd+=(-v $myhome:$myhome)
# add userid and groupid mappings:
cmd+=(-u $(id -u):$(id -g))

# then pass through any other arguments:
cmd+=("$@")

"${cmd[@]}"

This can be run as:

./runit.sh -it --rm alpine id

or, for a shell (alpine doesn't have bash by default):

./runit.sh -it --rm centos bash --login

You can throw in a -w $HOME to get it to start in the user's home directory, etc.

Anya Shenanigans
  • 91,618
  • 3
  • 107
  • 122
  • 1
    Mapping the auth files works great when the host is Ubuntu, but not at all when the host is Centos. That is true regardless of container O/S. I'm still struggling to figure out why. `ls -l /etc | grep passwd` prints a bunch of question marks. – Curt Feb 11 '20 at 09:00
  • It is also useful to map /etc/shadow:/etc/shadow:ro so that you can use `sudo` inside the container. – Curt Feb 11 '20 at 09:03
  • 1
    sounds like you don't have execute access on `/etc`, which is causing the issue on CentOS. Generally I don't map the shadow file because I'm not planning on elevating things running in the container - I use this procedure to run build scripts with my own userid, thus avoiding complications regarding things ending up owned as root in my home directory. I've evolved this procedure quite a bit to work on systems without entries in /etc, but it was done at work, so I can't share it directly. – Anya Shenanigans Feb 11 '20 at 10:41