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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github