The Docker exec command
docker exec This command executes a new command inside a running container. It is very useful for debugging, running additional processes, or performing management operations inside the container.
Syntax
docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
Common parameters
-d, --detach: Run the command in the background.--detach-keys: Override the key sequence for detaching from a container.-e, --env: Sets environment variables.--env-file: Read environment variables from a file.-i, --interactive: Keep standard input open.--privileged: Give this command extra privileges.--user, -u: Run the command as the specified user.--workdir, -w: Specify the working directory of the command.-t, --tty: Allocate a pseudo-TTY.
Example
Run a command inside a container:
docker exec my_container ls /app
Execute the ls /app command inside the running my_container container to list the contents of the /app directory.
Run a command in interactive mode:
docker exec -it my_container /bin/bash
Start an interactive Bash shell inside the running my_container container. -i keeps standard input open, and -t allocates a pseudo-TTY.
Run a command in the background:
docker exec -d my_container touch /app/newfile.txt
Execute the touch /app/newfile.txt command in the background inside the running my_container container to create a new file.
Set environment variables:
docker exec -e MY_ENV_VAR=my_value my_container env
Execute the env command inside the running my_container container and set the environment variable MY_ENV_VAR to my_value.
Run a command as a specified user:
docker exec -u user123 my_container whoami
Execute the whoami command as user user123 inside the running my_container container.
Specify the working directory:
docker exec -w /app my_container pwd
Execute the pwd command with /app as the working directory inside the running my_container container.
Use Cases
- Debug containers: Enter the container to debug and troubleshoot problems.
- Manage Tasks: Run additional management tasks or maintenance operations inside the container.
- Monitoring and inspection: Execute monitoring and inspection commands inside the container to obtain running status and logs.
Summary
docker exec This command is a very powerful tool in Docker that allows users to execute additional commands inside a running container. It is very useful for debugging, managing, and maintaining containers, helping users control and operate the environment inside a container more flexibly.
Docker Command Reference