Issue
I know that one can use the --user
option with Docker to run a container as a certain user, but in my case, my Docker image has a user inside it, let us call that user manager
. Now is it possible to map that user to a user on host? For example, if there is a user john
on the host, can we map john
to manager
?
Solution
Yes, you can set the user from the host, but you should modify your Dockerfile a bit to deal with run time user.
FROM alpine:latest
# Overide user name at build, if buil-arg no passed, will create user named `default` user
ARG DOCKER_USER=default_user
# Create a group and user
RUN addgroup -S $DOCKER_USER && adduser -S $DOCKER_USER -G $DOCKER_USER
# Tell docker that all future commands should run as the appuser user
USER $DOCKER_USER
Now, Build to Docker
docker build --build-arg DOCKER_USER=$(whoami) -t docker_user .
The new user in Docker will be the Host user.
docker run --rm docker_user ash -c "whoami"
Another way just pass the and map the host user without creating the user in Dockerfile.
export UID=$(id -u)
export GID=$(id -g)
docker run -it \
--user $UID:$GID \
--workdir="/home/$USER" \
--volume="/etc/group:/etc/group:ro" \
--volume="/etc/passwd:/etc/passwd:ro" \
--volume="/etc/shadow:/etc/shadow:ro" \
alpine ash -c "whoami"
You can further read more about the user in docker here and here.
Answered By - Adiii Answer Checked By - Gilberto Lyons (WPSolving Admin)