BY default when you run
docker run -it [myimage]
OR
docker attach [mycontainer]
you connect to the terminal as root user, but I would like to connect as a different user. Is this possible?
BY default when you run
docker run -it [myimage]
OR
docker attach [mycontainer]
you connect to the terminal as root user, but I would like to connect as a different user. Is this possible?
You can specify
USER
in the Dockerfile. All subsequent actions will be performed using that account. You can specifyUSER
one line before theCMD
orENTRYPOINT
if you only want to use that user when launching a container (and not when building the image). When you start a container from the resulting image, you will attach as the specified user.Execute command as www-data user:
docker exec -t --user www-data container bash -c "ls -la"
My solution:
This allows the user to run arbitrary commands using the tools provides by
my-docker-image
. Note how the user's current working directory is volume mounted to/cmd
inside the container.I am using this workflow to allow my dev-team to cross-compile C/C++ code for the arm64 target, whose bsp I maintain (the
my-docker-image
contains the cross-compiler, sysroot, make, cmake, etc). With this a user can simply do something like:Where
cross_compile.sh
is the script shown above. Theaddgroup/useradd
machinery allows user-ownership of any files/directories created by the build.While this works for us. It seems sort of hacky. I'm open to alternative implementations ...
The only way I am able to make it work is by:
So I have to both specify $USER environment variable as well a point the /etc/passwd file. In this way, I can compile in /siem folder and retain ownership of files there not as root.
For
docker run
:Simply add the option
--user <user>
to change to another user when you start the docker container.For
docker attach
ordocker exec
:Since the command is used to attach/execute into the existing process, therefore it uses the current user there directly.
If you really want to attach to the user you want to have, then
run --user <user>
or mention it in yourDockerfile
usingUSER
You can run a shell in a running docker container using a command like:
docker exec -it --user root <container id> /bin/bash