How to use the docker exec command to run commands in Docker containers
Docker containers have revolutionized the way we build, ship, and run applications. Containers provide a consistent environment for development, testing, and production – also, they simplify workflows and enhance portability.
Among Docker’s many features, the ability to interact with a running container is crucial. The docker exec command allows users to perform tasks directly inside a running container without disrupting its operation.
Download free docker cheat sheet
In this guide, we’ll explore how to use the docker exec command effectively. Whether you’re running a shell session, executing a single command, or performing advanced tasks like managing logs or passing environment variables, this article will walk you through the process with clear explanations and practical examples.
Prerequisites
Before trying out the docker exec command, ensure your environment meets the following prerequisites:
- Virtual Private Server (VPS): Access to a VPS is optional but highly recommended, as production environments require a hosting platform. If you don’t yet have one, Hostinger offers a range of VPS plans.
- Docker installed: You need to ensure Docker is installed and configured on your system.
- Docker container running: At least one running docker container is needed so you can run commands on it.
With these basics ready, you can start using docker exec to interact with containers.
Custom docker exec options
![Terminal showing outputs of docker exec help](https://www.hostinger.com/tutorials/wp-content/uploads/sites/2/2025/02/docker-exec-options-1024x470.png)
The docker exec command includes several options that allow you to customize how commands are executed inside a container. Here are the main docker exec flags:
- -i (interactive): Keeps STDIN open for interactive sessions.
- -t (tty): Allocates a pseudo-TTY (terminal), making it easier to run commands interactively.
- -d (detach): Runs the command in the background (detached mode).
- –env (environment variables): Sets environment variables for the executed command.
- –privileged: Grants extended privileges to the executed command.
- –user: Runs the command as a specific user (UID or username).
- –workdir: Sets the working directory inside the container for the command.
Example uses of docker exec
Now that we’ve covered the key options for the docker exec command, let’s explore practical examples of how to use it in real-world scenarios. The following sections will guide you through common tasks, like running a shell in a container, executing commands with root privileges, or setting environment variables.
Important! Docker commands often require sudo privileges. To simplify usage, you can configure Docker to run without sudo by adding your user to the Docker group. This guide omits sudo for brevity, but ensure you either prepend sudo to commands or set up Docker to not require it.
Running a shell in a container
One of the most common uses of the docker exec command is to access a running container’s shell. This allows you to interact with the container’s filesystem, execute commands directly, and perform troubleshooting or administrative tasks just like you would in a terminal window.
To start an interactive shell inside a container, use the following docker exec syntax:
docker exec -it container_name_or_id /bin/bash
Here’s a breakdown of the components:
- -i (interactive): Keeps the standard input (STDIN) open, allowing you to type commands.
- -t (terminal): Allocates a pseudo-terminal (TTY), which is necessary for running shell sessions.
When executed, this command starts a Bash shell session inside the container specified. You can then run commands as if you were directly logged into the container’s environment.
If the container doesn’t have Bash installed, you can use another shell, such as sh:
docker exec -it container_name_or_id /bin/sh
![Terminal window displaying shell session started on a docker container](https://www.hostinger.com/tutorials/wp-content/uploads/sites/2/2025/02/run-shell-1024x67.png)
This method is irreplaceable for debugging and exploring the internals of a container without stopping its operations.
Running a single command inside a container
The docker exec command can be used to run a single command inside a running container without opening a shell session. For example, to list the files in a container’s file system, you can use:
docker exec container_name_or_id ls
This command executes the ls command inside the specified container, listing the files and directories in the container’s default working directory:
![Terminal window displaying outputs of ls command executed on Docker container](https://www.hostinger.com/tutorials/wp-content/uploads/sites/2/2025/02/docker-ls-1024x194.png)
If you want to view files in a specific directory, include the directory path:
docker exec container_name_or_id ls /path/to/directory
This is a quick and efficient way to interact with a container for simple tasks, such as checking the contents of directories, without needing to start an interactive shell session.
Running background tasks
The docker exec command can also be used to run tasks in the background without keeping the terminal session active. This is done using the -d (detach) flag, which runs the command in detached mode.
For example, to run a command in the background inside a container:
docker exec -d container_name_or_id some_command
The detach flag -d ensures the command runs in the background, allowing you to continue using your terminal without waiting for the command to complete.
For instance, you can start a process to log system information inside the container:
docker exec -d container_name_or_id top
The top command will continue running in the background while your terminal remains free for other tasks. You can later use docker logs or other tools to check the output of background tasks if needed:
![Terminal window displaying usage of docker exec -d command](https://www.hostinger.com/tutorials/wp-content/uploads/sites/2/2025/02/exec-detached-1024x212.png)
This approach is especially useful for starting long-running processes or tasks inside a container without tying up your local terminal.
Passing environment variables
You can use the docker exec command with the –env flag to pass environment variables to a command executed inside a container. This is useful when a command requires specific configuration values or temporary overrides for its environment.
The syntax for this is:
docker exec --env VAR=value container_name_or_id command
Here’s an example:
docker exec --env GREETING="Hello, World!" container_name_or_id sh -c 'echo $GREETING'
In this case:
- –env VAR=value: Defines the environment variable (GREETING) and its value (Hello, World!).
- container_name_or_id: Specifies the container ID or name on which the command is executed.
- command: Starts a shell inside the container and runs the echo $GREETING command inside it.
When executed, the output will display “Hello, World!”:
![Terminal window displaying setting an environment variable and returning it with docker exec](https://www.hostinger.com/tutorials/wp-content/uploads/sites/2/2025/02/exec-env-variable-1024x91.png)
You can pass multiple environment variables by repeating the –env flag:
docker exec --env VAR1=value1 --env VAR2=value2 container_name_or_id command
This is a powerful way to temporarily inject variables into a container without modifying its configuration or restarting it.
Accessing a specific container’s logs
You can use the docker exec command to access logs stored within a container by reading the log files directly. This is particularly useful when a containerized application writes logs to a specific file rather than sending them to Docker’s standard logging system.
For example, to view a log file inside a container:
docker exec container_name_or_id cat /path/to/logfile
- container_name_or_id: Specifies the container ID or name on which the log file is located.
- cat /path/to/logfile: Reads and displays the content of the log file at the specified path inside the container.
For instance, if a web server container stores logs at /var/log/nginx/access.log, you can access them with:
docker exec container_name_or_id cat /var/log/nginx/access.log
This command outputs the log content directly to your terminal, allowing you to quickly inspect it without entering the container:
![Terminal window displaying docker exec usage to return logs](https://www.hostinger.com/tutorials/wp-content/uploads/sites/2/2025/02/access-logs-1024x93.png)
If the log file is large, you can use additional tools like tail to view only the most recent entries:
docker exec container_name_or_id tail -n 20 /var/log/nginx/access.log
This approach is a simple and effective way to check container-specific logs for debugging or monitoring purposes.
Interacting with services inside containers
The docker exec command allows you to interact with services running inside a container, such as restarting a service, checking its status, or managing its configuration. This is particularly useful for troubleshooting or performing administrative tasks.
Checking a service’s status
To check the status of a service, you can use:
docker exec container_name_o2r_id service service_name status
For example:
docker exec container_name_or_id service nginx status
This command displays whether the nginx service is active, running, or stopped within the container:
![Terminal window returning status of nginx service](https://www.hostinger.com/tutorials/wp-content/uploads/sites/2/2025/02/nginx-status-1024x59.png)
Restarting a service
To restart a service inside a container, use the service management command specific to the container’s operating system. For example, in a container running Ubuntu or Debian:
docker exec container_name_or_id service service_name restart
For example:
docker exec container_name_or_id service nginx restart
This command restarts the nginx service inside the specified container:
![Terminal window showing usage of docker exec to restart nginx](https://www.hostinger.com/tutorials/wp-content/uploads/sites/2/2025/02/nginx-restart-1024x55.png)
Important! On modern Linux distributions, you might need to use systemctl instead of service if it is available in the container:
docker exec container_name_or_id systemctl restart service_name
Not all containers include service management tools like service or systemctl. Some lightweight containers may require directly running the service’s binary or script.
These commands give you direct control over services inside the container, making it easy to manage their lifecycle without restarting the entire container.
Running commands with root privileges
By default, commands executed using docker exec run as the container’s default user, which may not always have administrative (root) privileges. To run commands with root privileges, you can use the -u flag to specify the root user explicitly.
docker exec -u root container_name_or_id command
For example, to install a package or edit a system file requiring root access:
docker exec -u root container_name_or_id apk update
In this case:
- -u root: Runs the command as the root user inside the container.
- apk update: Executes the update command with the elevated privileges needed to access system resources.
![Terminal window showing apk update ran with root access on a docker container](https://www.hostinger.com/tutorials/wp-content/uploads/sites/2/2025/02/exec-as-root-apk-update-1024x166.png)
Let’s say you want to change file ownership or permissions inside a Docker container. To do that you need to run:
docker exec -u root container_name_or_id chown user:user /path/to/file
Important! If the container runs with a non-root user by design, switching to the root user is essential for administrative tasks like modifying configurations, managing files, or installing system-level packages.
Always exercise caution when running commands as root, as improper changes can affect the container’s functionality.
Using the -u root flag ensures you have the necessary privileges to perform administrative tasks inside the Docker container.
Troubleshooting common issues with docker exec
While using docker exec is straightforward, you may encounter some issues. Below are tips to troubleshoot and resolve them.
Container not running
If you receive an error like “Error response from daemon: Container container_name_or_id is not running“, it means the container is stopped.
- Use the docker ps command to list all active containers. If the container isn’t listed, it’s not running.
docker ps
![Terminal window showing empty results of docker ps](https://www.hostinger.com/tutorials/wp-content/uploads/sites/2/2025/02/docker-ps-1024x58.png)
- Start the container using docker start:
docker start container_name_or_id
![Terminal window showing docker start command and the container shown in docker ps output](https://www.hostinger.com/tutorials/wp-content/uploads/sites/2/2025/02/docker-start-1-1024x253.png)
- If the container is running but still has issues, you can restart it with docker restart:
docker restart container_name_or_id
Permission issues
You might encounter permission errors when executing commands inside a Docker container, especially as a non-root user.
- Use the -u root option to execute the command with root privileges:
docker exec -u root container_name_or_id command
- Verify the permissions of the default user inside the Docker container. If necessary, switch to a user with appropriate access:
docker exec -u username container_name_or_id command
- Use the chmod or chown commands (with root privileges) to adjust file permissions if needed.
Other tips
- Ensure you’re using the correct container ID or name in your command. Use docker ps to confirm the container’s details:
docker ps -a
- If issues persist, inspect the Docker container logs to identify the root cause:
docker logs container_name_or_id
These tips should help you resolve the most common issues encountered when using docker exec or other Docker commands.
Conclusion
The docker exec command is an essential tool for managing and interacting with running Docker containers. It allows you to execute commands directly inside containers, enabling efficient debugging, troubleshooting, and administrative tasks.
In this guide, we covered:
- Basic usage of docker exec and its key options, such as -i, -t, and -d.
- Practical examples, such as running shell sessions, executing single commands, passing environment variables, managing services, and accessing running Docker container logs.
- Tips for using root privileges inside a Docker container and troubleshooting common issues like stopped containers or permission errors.
By mastering docker exec, you gain direct control over your containerized environments, making it easier to explore, maintain, and optimize applications.
How to use docker exec command FAQ
What is the docker exec command?
The docker exec command allows users to debug, run administrative tasks, and interact with services inside a running Docker container without stopping it.
How do I use docker exec?
To use docker exec, specify the container name or ID followed by the command you want to execute. For example:docker exec -it container_name ls
This will execute the ls command inside a container’s working directory.
Can I run multiple commands with docker exec?
Yes, you can run multiple commands using a shell inside docker exec. Use:docker exec container_name sh -c "command1 && command2"
This executes command1, and if it runs successfully, command2 will run next. You can also use the semicolon (;) to execute commands sequentially so that subsequent instructions will run whether or not the previous one fails.