Docker Tutorial · Docker Basics · Lesson 5 of 26

Logs, exec and inspect

Read a container's output, run commands inside it, and inspect its configuration while it runs.

Create a free account to save this page, take notes and track your progress. Sign in

Logs

Docker captures what the main process writes to stdout and stderr. docker logs NAME shows it; --tail 20 limits lines, -f follows. Applications in containers should log to stdout rather than to files.

exec

docker exec NAME COMMAND runs an extra process in a running container: docker exec -it web sh opens a shell for debugging. Changes you make this way are lost when the container is replaced, so fix problems in the image, not by hand.

inspect

docker inspect returns the container's full configuration and state as JSON; --format extracts fields.

Logs, exec and inspect
trap 'docker rm -f rc-logs > /dev/null 2>&1' EXIT
docker run -d --name rc-logs alpine:3.24 sh -c 'for i in 1 2 3; do echo "request $i ok"; done; echo "disk almost full" >&2; sleep 300' > /dev/null
sleep 1
echo "--- last 2 log lines (stdout and stderr):"
docker logs --tail 2 rc-logs 2>&1
echo "--- a command inside the running container:"
docker exec rc-logs sh -c 'ps -o pid,args | head -3'
echo "--- restart policy: $(docker inspect rc-logs --format '{{.HostConfig.RestartPolicy.Name}}')"

Output

--- last 2 log lines (stdout and stderr):
request 2 ok
request 3 ok
--- a command inside the running container:
PID   COMMAND
    1 sleep 300
    7 sh -c ps -o pid,args | head -3
--- restart policy: no

Run this on your computer — see “Get Started” for setup.

Test yourself

Where should an application in a container write its logs?

  1. To a file inside the container
  2. To stdout and stderr, so Docker and the platform collect them
  3. Nowhere
  4. To the image
Show answer

Answer: To stdout and stderr, so Docker and the platform collect them

Container platforms collect stdout/stderr; files inside the container disappear with it.

Was this page helpful?