Gaurav Koley Internet Lurker, Poet, Night Owl @ IIIT Bangalore

Root user in Docker Container

I have been playing around with Docker for a while. I use Docker for all of my Rails development and deployment tasks. So, every once in a while I encounter a situation where I have to enter the root user mode in the Docker container.

If you think that the solution to the above problem is simply:
$ docker run -it <container_name> sudo bash, then you will find that sudo is not included by default in most docker base images.

So what is the solution?

The current recommended solution, as of Docker 1.3 is to run the following command:

$ docker exec -u 0 -it <container_name_or_id> /bin/bash

Here, the -u 0 flag specifies that the root user with id 0 be used to run /bin/bash.

To run this command, your container needs to be running already.

If you wish to enter as root into an image, run the following command:

$ docker run -u 0 -it <image_name_or_id> /bin/bash

The above mentioned commands adhere to all the restrictions that your docker container adheres to.

There is also an alternative way which doesn’t enter the cgroups, and therefore evades resource limitations. The potential benefit of this would be debugging and external audit.

To do this, first determine the PID of your container on the host:

$ PID=`docker inspect --format {{.State.Pid}} <container_name_ID>`

Then use nsenter to enter the container as root

$ nsenter --target $PID --mount --uts --ipc --net --pid

And you will have access to a root shell in your desired container. This method works only for containers which are currently running.

Single line command:

$ nsenter --target `docker inspect --format  <container_name_or_ID>` --mount --uts --ipc --net --pid