How to use docker exec?

0143

To use the docker exec command, follow these steps:

  1. Identify the Running Container: First, you need to know the name or ID of the running container you want to interact with. You can list all running containers using:

    docker container ls
  2. Run a Command Inside the Container: Use the docker exec command to execute a command inside the container. The basic syntax is:

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

    Here are some common examples:

    • Start an Interactive Shell:

      docker exec -it <container_name_or_id> /bin/bash

      This command opens an interactive bash shell inside the specified container.

    • Run a Command:

      docker exec <container_name_or_id> ls /app

      This command lists the contents of the /app directory inside the specified container.

    • Run a Command with Environment Variables:

      docker exec -e VAR_NAME=value <container_name_or_id> printenv VAR_NAME

      This command runs printenv to display the value of the specified environment variable inside the container.

  3. Using Options: You can use various options with docker exec, such as:

    • -i: Keep STDIN open even if not attached.
    • -t: Allocate a pseudo-TTY.

Here’s a complete example of starting a bash shell in a running container named my_container:

docker exec -it my_container /bin/bash

This will give you a command prompt inside the container, allowing you to run commands as if you were logged into that container directly.

0 Comments

no data
Be the first to share your comment!