How to Run Docker exec Command in Docker Container? (Docker exec into Container)

To run a command inside a running Docker container, use:

docker exec -it <container_id> <command>

For example, to open a bash shell:

docker exec -it mycontainer bash

To run a single command:

docker exec mycontainer ls /app

Docker is a widely used open-source tool that simplifies application deployment, scaling, and management using container technology. With Docker Containers, developers can package applications and their dependencies into portable containers, ensuring consistency across different environments.

What does Docker exec do?

One of Docker's key commands is docker exec, which lets users execute commands inside a running container. This feature allows direct interaction with the container's processes and environment, making it useful for troubleshooting or managing applications.

Docker is versatile and compatible with various operating systems, including Linux, Windows, and macOS. It can even be installed on a Virtual Private Server (VPS). Setting up Docker requires following specific configuration steps tailored to your chosen platform.

How to Use docker exec Command?

Before using the docker exec command, ensure Docker is properly installed on your system. Then, identify the specific container where you want to run the command.

In this guide, you will explore the docker exec command. We will demonstrate how to run docker exec as root inside a docker container using different use cases.

Prerequisites

  • Verify that you have the latest version of Ubuntu installed on your system.
  • Install Docker by following the steps in Docker's official documentation.
  • Add your user to the Docker group to run Docker commands without needing to enter the administrator password each time.

Start a Docker Container

To illustrate how to use the docker exec command, we’ll first start a container. 

First, pull an image into a Docker container:

# docker pull redis

Here’s an example using a Redis container:

# docker run -d --name myredis redis

This command starts a Redis container in detached mode (-d flag), running it in the background. The container, named myredis, will serve as our example environment for executing commands.

Running Commands Inside a Docker Container (Docker Container)

You'll first need its container ID to execute commands within a container. You can find the container ID by listing all running containers using the following command:

# docker ps

Once you have the container ID (e.g., 6a8b7d170a12), you can use it to run commands inside the container.

Docker exec Command Syntax (Docker exec as root)

The general syntax of the docker exec command is:

docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

Here are the commonly used options:

-d, --detach: Runs the command in the background.

--detach-keys: Sets a custom key sequence to detach from the container.

-e, --env: Specifies environment variables for the command.

--env-file: Loads environment variables from a file.

-i, --interactive: Keeps the standard input (STDIN) open even if not attached to a terminal.

--privileged: Grants the command extended privileges.

-t, --tty: Allocates a pseudo-terminal for the command.

-u, --user: Runs the command as a specific user or UID.

-w, --workdir:Sets the working directory inside the container for the command.

Running docker exec into Container in Non-Interactive Mode (docker exec into container)

In non-interactive mode, you can execute a single command inside a running container. For example, to check the Redis version inside a running container, use the following command:

# docker exec <container_id> redis-server --version

This command runs the redis-server --version inside the specified container (replace <container_id> with the actual ID, e.g., 6a8b7d170a12). It retrieves and displays the Redis version directly in your terminal.

Running Commands in an Interactive Shell 

Interactive mode allows you to open a shell session inside a container, making it possible to run multiple commands and explore the container’s environment. To access an interactive shell, use the following syntax:

docker exec -it CONTAINER COMMAND [ARG...]

For example, to open a shell in a running Redis container, use:

# docker exec -it 6a8b7d170a12 bash

Replace <container_id> with the ID of your Redis container (e.g., 6a8b7d170a12). This command opens a shell session inside the container, letting you interact with the environment and execute multiple commands.

Example: Running a Command Inside the Interactive Shell (Docker bash)

Once inside the shell, you can execute Redis-specific commands. For instance:

# redis-cli ping

This command checks the status of the Redis server running within the container, returning PONG if it’s functioning correctly. You can now explore the container’s file system and environment as needed.

Running Docker exec as Different User (docker exec as user)

By default, commands are executed with docker exec as root inside the container. However, you can specify a different user for the command. To run a command as a specific user, use the following syntax:

docker exec -u USERNAME CONTAINER COMMAND [ARG...]

For example, to run the “whoami” command as the Redis user inside a Redis container, you would use:

# docker exec -u redis 6a8b7d170a12 whoami

Running Commands with Environment Variables

You can run commands inside a container while setting specific environment variables using the following syntax:

docker exec -e VAR_NAME=VAR_VALUE CONTAINER COMMAND [ARG...]

For instance, to run the env command inside a Redis container with a custom environment variable, use:

# docker exec -e MY_VARIABLE='testing_env' <container_id> env

This sets MY_VARIABLE to testing_env and then runs the env command to display the container's environment variables. This method is useful for passing sensitive data, such as API keys, securely into a container without exposing them in the container’s environment.

Docker Exec Examples (Common Use Cases)

The docker exec command allows you to run commands inside an active Docker container without stopping or restarting it. It is widely used for troubleshooting, maintenance, diagnostics, and one-time administrative operations. A typical docker exec example is opening an interactive shell inside a running container to inspect files, verify processes, or troubleshoot application issues.

Common docker exec use cases include:

 1. Opening a shell inside a running container.

Use docker exec -it with Bash or another shell to inspect files, processes, permissions, and the container environment.

 2. Viewing configuration files.

Administrators can check application settings, environment variables, mounted directories, and file permissions. Manual changes may be lost when the container is recreated, so permanent updates should be added to the image or mounted configuration.

 3. Running database commands.

docker exec is useful for launching database clients, executing SQL queries, applying migrations, creating backups, or performing maintenance tasks.

 4. Checking system information.

Commands such as ps, top, df, free, and env help diagnose resource usage, running processes, disk space, and environment settings.

 5. Clearing application caches.

Framework-specific cache commands can be executed after code, routing, template, or configuration changes.

 6. Testing network connectivity.

Tools such as curl, ping, wget, or nslookup help verify connections between containers, databases, APIs, and external services.

 7. Running maintenance scripts.

You can execute data imports, permission fixes, queue commands, scheduled task tests, and other one-time operations.

These Docker exec examples show why the command is essential for container debugging and administration. However, it should mainly be used for temporary tasks, while persistent changes belong in the Dockerfile, Docker Compose configuration, environment variables, or mounted volumes.

How to Enter a Running Docker Container

Sometimes you need to look inside a container while the application is still running. This may be necessary to check files, review configuration, test a command, inspect processes, or find the cause of an error. In most cases, entering a Docker container is done with docker exec, because it allows you to start a shell inside an existing container without recreating or stopping it.

Begin by checking which containers are currently active:

docker ps

Copy the required container name or ID, then open an interactive shell:

docker exec -it container_name /bin/bash

This command creates a terminal session inside the container. The -i option keeps the input stream open, while -t provides a usable terminal interface.

Not every image includes Bash. Minimal images, especially those based on Alpine Linux, often provide only the standard sh shell. In that case, use:

docker exec -it container_name /bin/sh

This is the usual approach when you need to exec into a Docker container and Bash is unavailable.

Users sometimes search for docker get into container or docker login into container, but these phrases can be misleading. The docker login command does not open a container. It is used to authenticate with Docker Hub or another container registry. To access the environment of a running container, docker exec is the correct command.

For a service started with Docker Compose, the syntax is slightly different:

docker compose exec service_name sh

Once inside, you can inspect directories, run diagnostic tools, verify environment variables, or perform one-time maintenance tasks. To close the shell, enter exit or press Ctrl + D. This ends only the interactive session; the container itself keeps running.

Docker Exec Shell: Bash vs Sh

When using a docker exec shell, one of the first decisions is whether to launch bash or sh. The correct choice depends on the operating system and tools included in the container image.

Bash is a feature-rich shell commonly available in Ubuntu, Debian, and similar distributions. It supports command history, tab completion, aliases, scripting features, and other tools that make troubleshooting and administration more convenient. If you need to docker bash running container, this is usually the preferred option:

docker exec -it container_name /bin/bash

However, many lightweight images, such as Alpine Linux, do not include Bash to keep the image size small. Instead, they provide the POSIX-compatible sh shell, which is sufficient for most administrative tasks:

docker exec -it container_name /bin/sh

If you are unsure which shell is available, try Bash first. If the command returns an error indicating that /bin/bash does not exist, simply use sh instead. This approach works with the majority of minimal Docker images.

In practice, both shells let you inspect files, check logs, edit configuration, and run commands inside a container. Bash offers a more comfortable interactive experience, while sh provides maximum compatibility across different container images.

Docker Exec vs Docker Run vs Docker Attach

Docker provides several commands for interacting with containers, but they solve different problems. Understanding when to use each one helps avoid common mistakes, especially when troubleshooting or managing production workloads.

Command

What it does

Creates a new container

Works with a running container

Typical use case

docker run

Creates and starts a new container from an image

Yes

No

Launching an application or service

docker exec

Starts a new command or shell inside an existing container

No

Yes

Debugging, maintenance, running one-time commands

docker attach

Connects to the container's main process and its standard input/output

No

Yes

Viewing or interacting with the primary application


For most administration and troubleshooting tasks, docker exec is the recommended choice because it lets you work inside a running container without interfering with its primary process.

Conclusion

This guide covered various ways to interact with Docker containers, including running commands non-interactively, accessing an interactive shell, using environment variables, and executing docker exec as root and as a different user. These methods offer flexibility in managing Docker containers. For more details, refer to the official Docker exec documentation.

Need a reliable environment for your containers? Deploy your Docker instances on BlueVPS.com high-performance servers with unlimited traffic, scalable resources, and a dedicated hosting environment.

 

Blog

FAQ How to Run Docker exec Command in Docker Container? (Docker exec into Container)