docker exec
The docker exec command is used to run a command in a running container. This allows you to execute commands inside a container that is already running.
Basic Syntax
Key Options and Parameters
-d, --detach: Run command in the background.
docker exec -d mycontainer touch /tmp/execWorks-i, --interactive: Keep STDIN open even if not attached.
docker exec -i mycontainer bash-t, --tty: Allocate a pseudo-TTY.
docker exec -t mycontainer bash-u, --user: Username or UID to run the command as.
docker exec -u root mycontainer bash-e, --env: Set environment variables.
docker exec -e "ENV_VAR=value" mycontainer bash-w, --workdir: Working directory inside the container.
docker exec -w /app mycontainer ls
Examples
Running a Command in a Container
docker exec mycontainer ls /appThis command lists the contents of the
/appdirectory inside the container namedmycontainer.Running a Command in the Background
docker exec -d mycontainer touch /tmp/execWorksThis command creates a file named
execWorksin the/tmpdirectory inside the container namedmycontainerand runs in the background.Running an Interactive Shell
docker exec -it mycontainer bashThis command starts an interactive bash shell inside the container named
mycontainer.Running a Command as a Different User
docker exec -u root mycontainer bashThis command starts a bash shell inside the container named
mycontaineras the root user.Setting Environment Variables
docker exec -e "ENV_VAR=value" mycontainer printenv ENV_VARThis command sets the environment variable
ENV_VARtovalueand prints it inside the container namedmycontainer.Specifying a Working Directory
docker exec -w /app mycontainer lsThis command lists the contents of the
/appdirectory inside the container namedmycontainer.
Conclusion
The docker exec command is essential for running commands in a running container. Understanding its options and parameters allows you to effectively manage and interact with your Docker containers.