Docker exec Command

Docker command reference


docker execThe command is used to execute a new command inside a running container. This is useful for debugging, running additional processes, or performing management operations inside the container.

Syntax

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

Common Parameters

  • -d, --detachRun the command in the background.
  • --detach-keys: Override the key sequence for detaching from a container.
  • -e, --env: Set environment variables.
  • --env-file: Read environment variables from a file.
  • -i, --interactive: Keep standard input open.
  • --privileged: Grant additional privileges to this command.
  • --user, -uRun the command as the specified user.
  • --workdir, -wSpecify the working directory for the command.
  • -t, --tty: Allocate a pseudo-TTY.

Example

Run the command inside the 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 the 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 the command in the background:

docker exec -d my_container touch /app/newfile.txt

Run 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, setting the environment variable MY_ENV_VAR to the value my_value.

Run the command as the specified user:

docker exec -u user123 my_container whoami

Execute the whoami command as 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 Case

  • Debug containerEnter the container to debug and troubleshoot issues.
  • Management tasks: Run additional administrative 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 execThe command is a very powerful tool in Docker that allows users to execute additional commands inside running containers. This is very useful for debugging, managing, and maintaining containers, helping users to more flexibly control and operate the environment inside containers.


Docker command reference

other extensions