Browse topics

Running a container

Version
29
Review
Draft

Summary#

docker run creates a new container from an image and starts it. In the foreground it waits for the main process and returns that process's exit status. --detach returns after the start, and --rm removes the container when it exits.

Syntax#

sh
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
docker run --rm --name NAME IMAGE COMMAND
docker run --detach --name NAME IMAGE COMMAND

Example#

The example uses a local alpine:3 image.

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

  docker run --pull never --rm --name "$name" alpine:3 echo "hello from a container"

  status=0
  docker run --pull never --rm --name "$name" alpine:3 sh -c 'exit 7' || status=$?
  echo "exit status: $status"

  docker run --pull never --detach --name "$name" alpine:3 sleep 60 >/dev/null
  docker container inspect --format 'state: {{.State.Status}}' "$name"
)

Expected output#

Text
hello from a container
exit status: 7
state: running

Common mistakes#

Put Docker options before the image name. Everything after the image is the command and its arguments, so docker run alpine:3 --rm tries to execute --rm inside the container and does not enable removal.

Version applicability#

Checked with Docker Engine 29. Exit statuses 125, 126 and 127 report a Docker error, a command that cannot be invoked and a command that cannot be found. A container command can also return those numbers itself.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0