ScanSkill

docker exec

The docker exec command runs a command in a running container.

Syntax

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

Here,

Options

  • -detach , -d → Detached mode: run command in the background
  • --detach-keys → Override the key sequence for detaching a container
  • --env , -e → Set environment variables
  • --env-file → Read in a file of environment variables
  • --interactive, -i → Keep STDIN open even if not attached
  • --privileged → Give extended privileges to the command
  • --tty , -t → Allocate a pseudo-TTY
  • --user , -u → Username or UID (format: <name|uid>[:<group|gid>])
  • --workdir , -w → Working directory inside the container

Examples

First, start the container if you haven’t already:

$ docker run --name cloudyfox_bash --rm -it cloudyfox /bin/bash

Then, execute the container:

$ docker exec -d cloudyfox_bash touch /tmp/cloudyfoxFile

Here, a new file /tmp/cloudyfoxFile will be created in the background.

Now, execute an interactive bash shell on the container:

$ docker exec -it cloudyfox_bash /bin/bash

It will create a new bash session in the container cloudyfox_bash.

Also, set an environment variable:

$ docker exec -it -e VAR=10 cloudyfox_bash /bin/bash

Note: This $VAR will only be valid on the current bash session.