Learning Center
Docker

Docker Exec: How to Use It to Run Commands in a Container

29 Jan 2025
Minhal Abbas
Minhal Abbas

Docker is an effective and versatile environment built to assist you in the matter of running, creating, as well as deploying apps within containers. One of the significant utilities in it is docker exec. It permits you to run code within a particular container. Furthermore, you can maintain as well as build a reliable, compact container through it. During creation or installation, it is significant to analyze different operations/configurations and examine the current condition or resolve bugs. Therefore, it offers an environment where commands can be run in dockerized apps.

This tutorial will cover docker exec, complete with possible use cases and explanations.

Prerequisites
Copy link

You must meet certain prerequisites before beginning the article:

  • Installation: Verify that Docker is already installed. If not, check our tutorial to install it.
  • Permissions: The user account should have permissions/privileges to run the script.
  • Running Container: A container needs to be accessible as well as running at the moment. Through the docker ps, you can determine the ID or name of the container.
  • General Concepts: You should be familiar with core concepts of Docker. Familiarity with Linux systems and Docker basics will help in troubleshooting any issues during configuration.

These requirements are necessary before beginning the setup.

Basic Introduction 
Copy link

docker exec permits greater control, enhanced privacy, as well as better security for your apps. It helps users with regarding, management, monitoring, and debugging running apps within the particular container. Explore its features to boost your productivity and automate workflows. In this way, you can run direct commands by performing several operations like opening sessions, shell commands, and even running scripts.

This significantly enhances workflow by enabling interaction with the active/operational app. You can address issues as well as make configurations without the need for a full container restart, which improves efficiency.

General Syntax 
Copy link

The general syntax is:

docker exec [OPTIONS] CONTAINER CODE [ARG...]
  • OPTIONS: These are flags for customizing the behaviour of the particular command. Several options are as below:

    • -i: It indicates STDIN is launched even if not connected.

    • -t: It addresses the allocation of a pseudo-TTY.

    • -u USER: It indicates the particular user for running the command.

    • -w WORKDIR: It indicates the directory which is working for the particular command.

  • CONTAINER: It indicates the container ID or name, where instructions are executed.

  • CODE:  This is the script or command that you require to run inside the container

  • ARG: It represents the additional parameters that are required to be passed to the particular CODE.

How to Use Docker Exec to Run Commands in a Container
Copy link

Through this utility, you can run programs, check logs, and perform other admin operations inside the particular running container by accessing its CLI. It is beneficial for effective management since it increases adaptability and gives more hold of dockerized apps.

Testing with a Sample Container
Copy link

Before running the specific command, you should have the minimum of one container that is currently operational. If you do not have it yet, execute the below command by with the particular container name. In our case, we use mynginx

docker run -d --name mynginx nginx

Image9

Finding the Active Container ID
Copy link

Before beginning, you are required to know the ID or name of the running container. Let’s run the below command to obtain the info on all dockerized apps that are currently operational:

docker ps

Image14

In the figure, the operational instance ID is b51dc8e05c77 and the name is mynginx

Working With a Particular Directory
Copy link

In this first example, you can run the command in the particular directory of the operational container. To achieve this, the --workdir or -w option is used by mentioning the folder name. Look at a use case where the pwd is run within the operational container mynginx:

docker exec --workdir /tmp mynginx pwd

Here:

  • docker exec: It is the core command to run the command within the operational container.
  • --workdir /tmp: This OPTION indicates our working directory.
  • mynginx: It indicates the CONTAINER name. 
  • pwd: It indicates the executed CODE within the container.

Image1

In the figure, the pwd executes within the particular mynginx instance and allocates the working directory to /tmp

Single Command Execution 
Copy link

In this example, execute a single command. For this, first mention the container name or ID, and afterwards, the particular command that you are required to execute. Here, mynginx is the name of the operational container, and the echo "Hello, Hostman Users!" is the command:

docker exec mynginx echo "Hello, Hostman Users!"

Image11

In the figure, there is an execution of the echo "Hello, Hostman Users!" command within mynginx.

Several Commands Execution 
Copy link

You can execute several commands in a single line statement by splitting them with semicolon. Let’s look at the below statement:

docker exec mynginx /bin/bash ls; free -m; df -h;

Image7

In the result, ls shows the content inside of the mentioned folder, free -m shows the system memory and df -h disk space usage. It permits you to analyze the memory state, filesystem, and other info in one statement.

Enabling the Shell Through Name
Copy link

You can enable the shell within the dockerized app. It permits an interface for the file system as well as script execution. Here, the -it option activates interactive mode and assigns the interface:

docker exec -it mynginx /bin/bash

Image17

The figure enables the bash shell interface within mynginx. But, /bin/bash is not guaranteed to be present in every image of Docker. Therefore, other shells like sh can also be enabled.

Now, input exit and press ENTER to close the interface:

exit

Image15

To launch other shells like sh (which is a symbolic link to bash or another shell), use /bin/sh in the below statement line:

docker exec -it mynginx /bin/sh

Image3

In the figure, the code line launches the shell interface, which is operational. 

Enabling the Shell Through ID
Copy link

In this particular use case, enable the session through the b51dc8e05c77 container ID inside the Docker app. Furthermore, you have the ability to interact with the interface as though you directly logged in via the -it flag. The -t indicates the assignment of pseudo-TTY, and the -i opens the STDIN. Both are beneficial for analysis, debugging, as well as managerial operations:

docker exec -it b51dc8e05c77 bash

Image5

Furthermore, you can analyse the information of the current folder inside the particular shell (in a detailed format), e.g., file size, owner, group, number of links, modification date, and file permissions:

ls -l

Image12

It gives detailed information on each file as well as the folder that assists you in knowing their attributes and managing them effectively.

Working As a Particular User
Copy link

You can execute a command as the specific user through the -u option. It is beneficial when you are permitted to work with specific privileges. It runs the command in the operational container through the particular user and group:

docker exec -u <user>:<group> <container_id> <command> 

For instance, the whoami runs as the www-data in the mynginx container:

docker exec -u www-data mynginx whoami

Image6

In the figure, www-data verifies that the particular command is executed successfully with the correct user permissions and within the expected interface. 

Enabling a Non-Interactive Shell
Copy link

Sometimes, users prefer not to have any interaction. For such circumstances, they can execute the command without any argument:

docker exec mynginx tail /etc/passwd 

Image10

The last 10 lines of the passwd file have been shown. This passwd file is stored in the /etc/passwd folder containing the user information. It helps you monitor the user account information, permitting you to quickly check for troubleshooting or update issues. 

Working With a Single Environment Variable
Copy link

You may need to pass environment variables to the command that is run in the operational container. To achieve this, use the -e option as below:

docker exec -e MY_VAR=value mynginx printenv MY_VAR

Image2

In the figure, the printenv MY_VAR is successfully executed in mynginx when the MY_VAR is set to value correctly.

Working With Multiple Environment Variables
Copy link

You can set more than one variable through the -e flag. 

docker exec -e TEST=john -e ENVIRONMENT=prod mynginx env

Image8

The figure confirms that the two variables TEST and ENVIRONMENT have been set to john and prod in the mynginx.

Working With the Detached Mode
Copy link

You can run commands in the detached mode through the -d flag. Therefore, it runs in the background:

docker exec -d mynginx sleep 500

Image13

The figure confirms that the mynginx is executing the sleep 500 command.

Working With the Privileged Mode
Copy link

Here, the --privileged flag permits you to execute the command, such as mount, with elevated privileges in the running container:

docker exec --privileged mynginx mount

Image4

In the figure, mount permits the system to create a mount point with the particular permissions in the mynginx.

More Information on docker exec
Copy link

The --help option shows the manual with a list of available options with concise explanations. 

docker exec --help

Image16

Final Words
Copy link

docker exec is an effective utility for controlling and interacting with active containers. It is helpful for operations like monitoring, managing, and debugging apps without interfering with their functionality. It permits you to run code, launch shells, customize several configuration aspects, and also set environment variables. Once you become familiar with the usage of this utility, you can manage containers easily. It makes your operations much smoother for creating and deploying apps.