How to use docker container exec command to execute commands in a running container

DockerDockerBeginner
Practice Now

Introduction

In this lab, you will learn how to effectively use the docker container exec command to execute commands within a running Docker container. We will begin by starting a container for execution, then explore how to execute a single command in a running container and how to launch an interactive shell for more complex interactions.

Furthermore, this lab will cover how to customize the execution environment by setting environment variables and specifying the working directory for the exec process, providing you with the skills to manage and interact with your running containers.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL docker(("Docker")) -.-> docker/ContainerOperationsGroup(["Container Operations"]) docker(("Docker")) -.-> docker/ImageOperationsGroup(["Image Operations"]) docker/ContainerOperationsGroup -.-> docker/run("Run a Container") docker/ContainerOperationsGroup -.-> docker/ps("List Running Containers") docker/ContainerOperationsGroup -.-> docker/exec("Execute Command in Container") docker/ImageOperationsGroup -.-> docker/pull("Pull Image from Repository") subgraph Lab Skills docker/run -.-> lab-555108{{"How to use docker container exec command to execute commands in a running container"}} docker/ps -.-> lab-555108{{"How to use docker container exec command to execute commands in a running container"}} docker/exec -.-> lab-555108{{"How to use docker container exec command to execute commands in a running container"}} docker/pull -.-> lab-555108{{"How to use docker container exec command to execute commands in a running container"}} end

Start a container for execution

In this step, you will learn how to start a Docker container and execute a command within it. Docker containers are lightweight, portable, and self-sufficient units that encapsulate an application and its dependencies.

First, let's pull the ubuntu image from Docker Hub. This image contains a minimal Ubuntu operating system environment.

docker pull ubuntu:latest

You should see output indicating that the image is being downloaded. Once the download is complete, you can start a container based on this image and execute a simple command. We will use the echo command to print a message.

docker run ubuntu:latest echo "Hello from Docker container!"

Let's break down this command:

  • docker run: This is the command to create and start a new container.
  • ubuntu:latest: This specifies the image to use for the container. ubuntu is the image name, and latest is the tag, indicating the most recent version.
  • echo "Hello from Docker container!": This is the command that will be executed inside the container.

You should see the output Hello from Docker container! printed to your terminal. This confirms that the container was started and the command was executed successfully.

Execute a command in the running container

In the previous step, we started a container and executed a command that ran and then the container exited. In this step, we will learn how to execute a command inside a container that is already running. This is useful for inspecting the state of a running container or performing administrative tasks.

First, let's start a container that will keep running. We will use the ubuntu image again and run a command that keeps the container alive, like sleep infinity.

docker run -d ubuntu:latest sleep infinity

Let's look at the options used:

  • -d: This option runs the container in detached mode, meaning it runs in the background and doesn't block your terminal.
  • sleep infinity: This command inside the container will make it sleep indefinitely, keeping the container running.

Now, let's get the Container ID of the running container. You can use the docker ps command to list running containers.

docker ps

You should see output similar to this, showing your running container:

CONTAINER ID   IMAGE          COMMAND           CREATED         STATUS         PORTS     NAMES
<container_id>   ubuntu:latest   "sleep infinity"   About a minute ago   Up About a minute             <container_name>

Copy the CONTAINER ID from the output. Now, we can use the docker exec command to execute a command inside this running container. Replace <container_id> with the actual ID you copied.

docker exec / < container_id > ls

This command will execute ls / inside the specified container, listing the contents of the root directory within the container's filesystem. You should see a list of directories and files, similar to what you would see on a Linux system.

This demonstrates how to execute a command in a running container without stopping or restarting it.

Execute an interactive shell in the running container

In the previous step, we executed a single command in a running container. Often, you might need to interact with a running container more extensively, perhaps to debug an issue or explore its filesystem. In this step, you will learn how to open an interactive shell session inside a running container.

We will continue to use the ubuntu container that you started in the previous step. If the container is not running, you can start it again using the command from the previous step:

docker run -d ubuntu:latest sleep infinity

Get the Container ID of your running ubuntu container using docker ps:

docker ps

Now, use the docker exec command with the -it options to open an interactive terminal session inside the container. Replace <container_id> with the actual ID of your running container.

docker exec -it < container_id > bash

Let's look at the new options:

  • -i: This option keeps STDIN open even if not attached. This is necessary for interactive sessions.
  • -t: This option allocates a pseudo-TTY, which is required for a shell session.
  • bash: This is the command to execute inside the container, in this case, the Bash shell.

After running this command, your terminal prompt should change, indicating that you are now inside the container's Bash shell. You can now execute commands within the container's environment. For example, try listing the files in the current directory:

ls

You are now interacting directly with the container's filesystem and environment. To exit the container's shell and return to your host machine's terminal, simply type exit:

exit

You should now be back in your original terminal session. This interactive shell access is a powerful tool for debugging and managing your containers.

Set environment variables for the exec process

In this step, you will learn how to set environment variables specifically for the command being executed with docker exec. This allows you to pass configuration or other information to the process running inside the container without modifying the container's environment permanently.

We will continue to use the running ubuntu container from the previous steps. If it's not running, start it with:

docker run -d ubuntu:latest sleep infinity

Get the Container ID of your running ubuntu container using docker ps:

docker ps

Now, let's execute a command inside the container and set an environment variable for that specific execution. We will use the printenv command to display environment variables. Replace <container_id> with your container's ID.

docker exec -e MY_VARIABLE="Hello from LabEx" MY_VARIABLE < container_id > printenv

Let's look at the new option:

  • -e MY_VARIABLE="Hello from LabEx": This option sets an environment variable named MY_VARIABLE with the value "Hello from LabEx" for the printenv command being executed.

You should see the output Hello from LabEx printed to your terminal. This confirms that the environment variable was successfully set for the printenv process.

To demonstrate that this environment variable is only set for the exec process and not the container's main process, let's execute printenv MY_VARIABLE again without the -e option:

docker exec MY_VARIABLE < container_id > printenv

This time, you should not see any output, or potentially an error indicating that the variable is not set. This shows that the environment variable was only available to the command executed with the -e flag.

Setting environment variables with docker exec -e is a convenient way to pass dynamic configuration to processes running inside your containers.

Set the working directory for the exec process

In this final step, you will learn how to set the working directory for the command being executed with docker exec. By default, docker exec runs commands in the container's configured working directory (often /). You can override this using the -w option.

We will continue to use the running ubuntu container. If it's not running, start it with:

docker run -d ubuntu:latest sleep infinity

Get the Container ID of your running ubuntu container using docker ps:

docker ps

Now, let's execute a command that prints the current working directory inside the container. We will use the pwd command. Replace <container_id> with your container's ID.

docker exec < container_id > pwd

You should see / as the output, which is the default working directory in the ubuntu image.

Now, let's execute the pwd command again, but this time we will set the working directory to /tmp using the -w option.

docker exec -w /tmp < container_id > pwd

Let's look at the new option:

  • -w /tmp: This option sets the working directory for the pwd command to /tmp inside the container.

You should now see /tmp as the output. This demonstrates that you can specify a different working directory for the command executed with docker exec. This is useful when you need to execute commands that operate on files in a specific location within the container.

This concludes the lab on executing commands in Docker containers. You have learned how to start containers for execution, execute commands in running containers, open interactive shell sessions, set environment variables, and set the working directory for exec processes.

Summary

In this lab, you learned how to start a Docker container and execute a command within it using docker run. You then progressed to executing commands inside an already running container using the docker container exec command, which is essential for inspecting or managing active containers.

Furthermore, you explored advanced functionalities of docker container exec, including setting environment variables for the executed process and specifying the working directory, providing greater control and flexibility when interacting with running containers.