How to view logs for a docker image?

Ville Miekk-oja picture Ville Miekk-oja · Jun 15, 2016 · Viewed 50.5k times · Source

In the docker world, one can easily see logs for docker container (that is, a running image). But during image creation, one usually issues multiple commands. For example npm install commands in node projects. It would be beneficial to see logs for those commands as well. I quickly searched from the documentation, but didn't find how one can obtain logs for docker image. Is it possible?

Answer

BMitch picture BMitch · Jun 15, 2016

Easiest method is to use tee to send a copy of all your command output to a logfile. If you want it attached to the image, output your run commands to a logfile inside of the image with something like:

RUN my-install-cmd | tee /logs/my-install-cmd.log

Then you can run a quick one-off container to view the contents of the logs:

docker run --rm my-image cat /logs/my-install-cmd.log

If you don't need the logs attached to the image, you can log the output of every build with a single change to your build command (instead of lots of changes to the run commands) exactly as JHarris says:

docker build -t my-image . | tee my-image.build.log

If you build without using --rm=true, then you have all the intermediate containers, and each one of those has a log you can review with

docker logs $container_id

And lastly, don't forget there's a history of the layers in the image. They don't show the output of each command, but it is useful for all of those commands that don't log any output and knowing which build each layer comes from particularly when there's lots of caching being used.

docker history my-image