Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 658
Andy59469 Avatar asked Mar 01 '16 22:03

Andy59469


People also ask

How do I run a docker container as a different user?

Running Commands as a Different User in a Docker Container To run a command as a different user inside your container, add the --user flag: docker exec --user guest container-name whoami.

How do I login as docker as a root user?

As an alternative, we can also access the Docker container as root. In this case, we'll use the nsenter command to access the Docker container. To use the nsenter command, we must know the PID of the running container. This allows us to access the Docker container as a root user and run any command to access any file.

Do you need root for docker?

Rootless mode allows running the Docker daemon and containers as a non-root user to mitigate potential vulnerabilities in the daemon and the container runtime. Rootless mode does not require root privileges even during the installation of the Docker daemon, as long as the prerequisites are met.

How do I run a user as container?

For docker run : Simply add the option --user <user> to change to another user when you start the docker container. 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.


2 Answers

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
like image 160
Larry Cai Avatar answered Sep 30 '22 20:09

Larry Cai


You can run a shell in a running docker container using a command like:

docker exec -it --user root <container id> /bin/bash

like image 26
Jason Avatar answered Sep 30 '22 19:09

Jason