To use the docker exec command, follow these steps:
-
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 -
Run a Command Inside the Container: Use the
docker execcommand 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/bashThis command opens an interactive bash shell inside the specified container.
-
Run a Command:
docker exec <container_name_or_id> ls /appThis command lists the contents of the
/appdirectory inside the specified container. -
Run a Command with Environment Variables:
docker exec -e VAR_NAME=value <container_name_or_id> printenv VAR_NAMEThis command runs
printenvto display the value of the specified environment variable inside the container.
-
-
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.
