Connect to docker container as user other than root

Andy59469 picture Andy59469 · Mar 1, 2016 · Viewed 104.2k times · Source

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?

Answer

Larry Cai picture Larry Cai · Mar 2, 2016

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

  1. start with that user run --user <user> or mention it in your Dockerfile using USER
  2. change the user using `su