How do I run a command on an already existing Docker container?

Better Stack Team
Updated on April 7, 2023

To run a command on an already existing Docker container, you can use the docker exec command. The docker exec command allows you to run a command in a running container.

The basic syntax of the docker exec command is:

  • OPTIONS: Optional flags for the docker exec command.
  • CONTAINER: The name or ID of the container you want to run the command in.
  • COMMAND: The command you want to run in the container.
  • ARG: Additional arguments to pass to the command.

For example, to run a command in a container with the name my-container, you can use the following command:

docker exec -it my-container command

In this example, the -it flag is used to allocate a new pseudo-TTY for the command. The command argument is the command you want to run in the container.

If you want to run a command as the root user, you can add the -u root flag to the docker exec command:

docker exec -it -u root my-container command

This will run the command as the root user in the my-container container.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack