Browse topics

Listing containers and reading logs

Version
29
Review
Draft

Summary#

docker ps lists running containers, and --all includes the others. docker logs prints what a container wrote to standard output and standard error, including after it has exited, when its logging driver keeps readable logs.

Syntax#

sh
docker ps --all --filter label=KEY=VALUE --format '{{.Names}} {{.State}}'
docker logs --tail 100 CONTAINER
docker logs --follow --since 10m --timestamps CONTAINER

Example#

The example uses a local alpine:3 image.

sh
(
  set -eu
  prefix="dlr-docker-commands-ps-$$"
  label="dlr-docker-commands-ps=$$"
  trap 'docker rm -f "$prefix-job" "$prefix-idle" >/dev/null 2>&1 || true' EXIT

  docker run --pull never --name "$prefix-job" --label "$label" --label role=job --log-driver local \
    alpine:3 sh -c 'echo one; echo two; echo three' >/dev/null
  docker run --pull never --detach --name "$prefix-idle" --label "$label" --label role=idle \
    alpine:3 sleep 60 >/dev/null

  echo "running:"
  docker ps --filter "label=$label" --format '{{.Label "role"}} {{.State}}'
  echo "all:"
  docker ps --all --filter "label=$label" --format '{{.Label "role"}} {{.State}}' | sort
  echo "last two log lines:"
  docker logs --tail 2 "$prefix-job"
)

Expected output#

Text
running:
idle running
all:
idle running
job exited
last two log lines:
two
three

Common mistakes#

For a container without a TTY, docker logs CONTAINER | grep error searches only its standard output. Use docker logs CONTAINER 2>&1 | grep error to search both streams. A container started with -t already has its output streams combined.

Version applicability#

Checked with Docker Engine 29. .State is a short value such as running or exited. .Status adds elapsed time, so it is a poor choice for scripts that compare text.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0