Browse topics

Running commands in a container

Version
29
Review
Draft

Summary#

docker exec starts an additional process in a running container. It can set variables, a user and a working directory for that process only, and it returns the command's exit status.

Syntax#

sh
docker exec -it CONTAINER sh
docker exec --env KEY=VALUE --workdir /path --user UID CONTAINER COMMAND [ARG...]
docker exec -i CONTAINER COMMAND < input.txt

Example#

The example uses a local alpine:3 image.

sh
(
  set -eu
  name="dlr-docker-commands-exec-$$"
  trap 'docker rm -f "$name" >/dev/null 2>&1 || true' EXIT

  docker run --pull never --detach --name "$name" --env STAGE=dev alpine:3 sleep 60 >/dev/null

  docker exec "$name" sh -c 'echo "stage=$STAGE dir=$(pwd)"'
  docker exec --env STAGE=test --workdir /tmp "$name" \
    sh -c 'echo "stage=$STAGE dir=$(pwd)"'
  printf 'alpha\nbeta\n' | docker exec -i "$name" wc -l

  status=0
  docker exec "$name" sh -c 'exit 3' || status=$?
  echo "exit status: $status"
)

Expected output#

Text
stage=dev dir=/
stage=test dir=/tmp
2
exit status: 3

Common mistakes#

The command must be an executable with separate arguments. docker exec CONTAINER "cd /tmp && ls" fails because Docker looks for a program with that whole name. Use docker exec CONTAINER sh -c 'cd /tmp && ls'. Use -i for piped input and reserve -t for an interactive terminal.

Version applicability#

Checked with Docker Engine 29. The container must be running and not paused. A process started by docker exec is not started again when the container restarts, and an image without a shell cannot run sh.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0