Docker

Docker Exec into Container as Root

Docker is a powerful containerization tool that allows users to create isolated and standalone applications. Docker containers carry the base operating system, the applications, and all required packages. Hence, in some instances, we need to have access to the systems shell, execute commands and perform custom configurations. Luckily, Docker provides us with the functionality to run commands in running containers.

This tutorial aims to show you how to work with the Docker exec command to execute commands in running containers.

Basic Usage

Working with Docker exec is very simple. We start by calling the docker exec command followed by the container name or id and the command to execute.

For example, to run the echo command in container Debian, we use the command as:

$ docker exec debian echo hello

The command spawns a shell of the Debian container and executes the echo command. An example output appears below:

To get the name or an ID of the running containers, use the command:

$ docker ps

Docker Exec Options

Docker exec command supports various options to modify the functionality of the commands. It supports the following functions.

  • -i – This option keeps the STDIN.
  • -t – Spawns a pseudo TTY
  • -u – Specifies the username or UID.
  • -w – Working directory
  • -p – allocates extended privileges to the command.
  • -d – runs in detached mode.
  • -e – sets environment variables.

Docker Exec Sh

In most cases, we need a shell instance into the container to execute raw commands. To do this, we use the docker exec command.

$ docker exec debian -i -t /bin/bash

The command above launches an interactive shell. It is good to ensure bash executable exists before the running command.

If bash or any shell you wish to use is unavailable, use sh in the command below:

$ docker exec -it /bin/sh

As you can see, you have an interactive shell session where you can execute commands.

Exec as Root

To exec command as root, use the -u option. The option requires a username or UID of the user. For example:

$ docker exec -u 0 debian whoami

$ root

In the above command, we use the UID of the root user to execute the whoami command as root.

To use the username instead of the user UID, use the command:

$ docker exec -u root debian whoami

$ root

The command above can help when you want to troubleshoot or perform tasks that require elevated privileges.

Conclusion

That is all for the docker exec command.

We have discussed using docker exec to run commands in your running containers and spawn a shell session. Finally, we covered how to run commands as root using username and UID.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list