How to run additional commands inside a docker container

In the Docker ecosystem, understanding how to interact with running containers is a fundamental skill. Sometimes, you need to execute additional commands in a container that’s already up and running. Docker provides a command that makes this not only possible but also straightforward. In this article, we’ll explore the docker exec command and how it can be used to interact with containers.

The docker exec Command

The docker exec command allows you to run commands in a container that is already started. Whether you need to debug an issue, modify a configuration, or simply check the state of your application, docker exec is the tool for the job.

Here’s the basic syntax:

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

Breaking Down the Command

  • docker: This is the base command that calls the Docker CLI.
  • exec: A sub-command of docker that tells it to execute a new command in a running container.
  • -it: These are combined options where -i attaches the terminal to the container’s STDIN, allowing interactive input, and -t allocates a pseudo-TTY, which makes it possible to emulate a terminal.
  • CONTAINER: This is the ID or name of the container where the command should be executed.
  • COMMAND: The command you want to run inside the container.

Interactive Shell Example

One of the most common uses of docker exec is to start an interactive shell inside a container. For instance, if you want to interact with a bash shell, you could use:

docker exec -it <container_id> /bin/bash

This command will start a bash session inside the container, allowing you to run bash commands as if you were inside a regular Linux terminal.

Practical Use Cases

  • Configuration: Perhaps you need to edit a configuration file using vi or nano. You can hop into the container, make your changes, and exit without affecting the container’s state.
  • Database Management: You might want to check the state of a database running in a container. Using docker exec, you can access the database CLI and perform any necessary queries or operations.
  • Log Checking: To quickly view logs, you can execute cat or tail on the log files within the container.

Tips and Considerations

  • Non-Interactive Commands: If you don’t need an interactive shell, omit the -t option.
  • Permissions: Sometimes, you may need to run commands as the root user or another user. You can use the --user option to specify which user the command should run as.
  • Security: Be cautious when executing commands that might affect the security or stability of the container.

,