Connect to docker container as user other than root
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?
Solution 1:
For docker run
:
Simply add the option --user <user>
to change to another user when you start the docker container.
docker run -it --user nobody busybox
For docker attach
or docker exec
:
Since the command is used to attach/execute into the existing process, therefore it uses the current user there directly.
docker run -it busybox # CTRL-P/Q to quit
docker attach <container id> # then you have root user
/ # id
uid=0(root) gid=0(root) groups=10(wheel)
docker run -it --user nobody busybox # CTRL-P/Q to quit
docker attach <container id>
/ $ id
uid=99(nobody) gid=99(nogroup)
If you really want to attach to the user you want to have, then
- start with that user
run --user <user>
or mention it in yourDockerfile
usingUSER
- change the user using `su
Solution 2:
You can run a shell in a running docker container using a command like:
docker exec -it --user root <container id> /bin/bash
Solution 3:
As an updated answer from 2020. --user , -u option is Username or UID (format: <name|uid>[:<group|gid>]).
Then, it works for me like this,
docker exec -it -u root:root container /bin/bash
Reference: https://docs.docker.com/engine/reference/commandline/exec/
Solution 4:
You can specify USER
in the Dockerfile. All subsequent actions will be performed using that account. You can specify USER
one line before the CMD
or ENTRYPOINT
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.