Execute a command in a container in Docker

Learn how to execute commands inside a Docker container using the docker exec command.

M Bytes Newsletter
Get the developer newsletter

    Fresh bytes every Thursday. No spam, ever. Unsubscribe anytime.

    Join 9,000+ developers and get three free video lessons every week.

    The docker exec command lets you execute any command that you normally would from command line, but have it executed within a specific container. This is particularly useful when you need to debug issues, check logs, or make changes directly within a container's environment.

    The basics syntax is:

    docker exec <container-name or container-id> <command>

    First, we need to find out which containers are running. We can get a list of them by using:

    docker ps
    # or more easily to remember:
    docker container ls

    We’ll see the id and name of all running containers.

    Now, we can execute a command inside one of these containers with the exec command, referencing either the id or the name of the container we want to run the command in:

    docker exec mycontainer ls

    And if the container provides a bash shell, which most containers do, we can also drop directly into an interactive shell with the -it flag, coupled with the bash command:

    docker exec -it mycontainer bash

    You can only exec into running containers, so if the command isn’t working, double check to see if you are referencing the correct container id or name, and that it is in fact running.

    The -it flag:

    • i keeps the connection interactive (so your commands actually work)
    • t gives you a proper terminal experience (so everything looks right)

    You are now essentially remoted into the container, and can execute any command that exists within it.

    When you're done, just type exit to pop back to your host system.