Retrieving container logs

It is a best practice for any good application to generate some logging information that developers and operators alike can use to find out what the application is doing at a given time, and whether there are any problems to help pinpoint the root cause of the issue.

When running inside a container, the application should preferably output the log items to STDOUT and STDERR and not into a file. If the logging output is directed to STDOUT and STDERR, then Docker can collect this information and keep it ready for consumption by a user or any other external system.

To access the logs of a given container, we can use the docker container logs command. If, for example, we want to retrieve the logs of our quotes container, we can use the following expression:

$ docker container logs quotes  

This will retrieve the whole log produced by the application from the very beginning of its existence.

Stop, wait a second—this is not quite true, what I just said. By default, Docker uses the so-called json-file logging driver. This driver stores the logging information in a file. And if there is a file rolling policy defined, then docker container logs only retrieves what is in the current active log file and not what is in previous, rolled files that might still be available on the host.

If we want to only get a few of the latest entries, we can use the -t or --tail parameter, as follows:

$ docker container logs --tail 5 quotes 

This will retrieve only the last five items the process running inside the container produced.

Sometimes, we want to follow the log that is produced by a container. This is possible when using the parameter -f or --follow. The following expression will output the last five log items and then follow the log as it is produced by the containerized process:

$ docker container logs --tail 5 --follow quotes