Managing containers: ps, logs, exec, stop

Docker · Essentials · 10 min

Day-to-day work with containers is mostly these commands.

Once containers are running you need to see and control them.

  • docker ps lists running containers; docker ps -a includes stopped ones. Each has an ID (any unique prefix works) and a name.
  • docker logs api prints what the main process wrote to stdout and stderr. -f follows, --tail 100 limits, --since 10m filters by time. This is why containerized apps should log to stdout rather than to files.
  • docker exec -it api sh runs an additional process in a running container, here a shell, so you can poke around. Use bash if the image has it. exec only works while the container is running.
  • docker stop api sends SIGTERM to the main process, waits (10 seconds by default, -t to change), then sends SIGKILL. Apps should handle SIGTERM to shut down gracefully.
  • docker kill api sends SIGKILL immediately.
  • docker start api / docker restart api start a stopped container again, keeping its writable layer.
  • docker rm api deletes a stopped container; docker rm -f api stops and deletes it.
  • docker inspect api dumps full JSON details: state, exit code, IP address, mounts, env. Use --format to pick fields.
  • docker stats shows live CPU and memory per container.

Containers that stop keep existing until removed, so docker ps -a grows over time. docker container prune removes all stopped containers in one go.

Example

docker run -d --name api -p 8000:8000 python:3.13 python -m http.server
docker ps                         # running containers
docker logs -f --tail 20 api      # follow output (Ctrl+C stops following)
docker exec -it api bash          # shell inside; exit to leave
docker exec api ls /              # one-off command
docker inspect api --format '{{.State.Status}} {{.NetworkSettings.IPAddress}}'
docker stop api                   # SIGTERM, then SIGKILL after 10 s
docker ps -a --filter name=api    # Exited (...)
docker start api && docker restart api
docker rm -f api
docker container prune            # remove all stopped containers

Remember

  • ps lists; logs shows stdout/stderr; exec runs extra processes inside
  • stop = SIGTERM, then SIGKILL after a grace period
  • Stopped containers persist until docker rm or prune
  • inspect --format pulls any detail out of the JSON

Watch out for

  • Expecting docker logs to show files the app writes to /var/log — it only captures stdout and stderr.

Check yourself

  1. What does docker stop do first?
  2. Which command opens a shell inside an already running container named db?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.docker.com/reference/cli/docker/container/exec/