Logs and getting inside

Where to find the program's output and how to look at a container from the inside.

Docker collects everything the main process writes to standard output and standard error. docker logs shows this output, the -f flag follows new lines, --tail 100 limits how far back it starts, and --since 10m shows only recent entries. That is why applications in containers write logs to stdout and stderr rather than to files: that way they show up in docker logs and are easy to ship to a central log system.

docker logs --tail 50 -f api
docker exec -it api sh
docker exec api env

docker exec runs an additional command inside an already running container. With -it you get an interactive shell and can look at files, variables and processes. A stopped container cannot accept exec: you have to start it first.

Minimal images may not even contain bash, so try sh. If the image has no shell at all, which is normal for very small images, docker cp helps to copy files out, and so does docker inspect, which shows the container's settings: environment variables, mounted volumes, network and the last exit code.

For a quick look at resources there is docker stats: a live table of memory and CPU usage per container. If a container is hitting its memory limit, you see it here before it crashes with code 137.

A common mistake is to fix a problem through docker exec: tweak a config inside the running container and forget about it. After the container is recreated, the fix disappears because it is neither in the image nor in the start settings. exec is a diagnostic tool. The fix goes into the Dockerfile, the environment variables or the mounted files.

Practice

  1. Where to write logs

    Where is the best place for an application in a container to write its logs?

    • To a file inside the container
    • To standard output and standard error
    • To a separate image
    • Only to a database
  2. What docker exec can do

    Which statements about docker exec are true? Mark all.

    • Runs an additional command in a running container
    • Works with a stopped container
    • With the -it flags gives an interactive shell
    • Saves changes to the image the container was started from
  3. Following the logs

    Which docker logs flag lets you follow new lines in real time? Write the flag.