/ QUICK TIPS , DOCKER

Docker logs from last run container

Running Docker containers is what we do often, so it’s good to know how to do it to see Docker logs immediately.

Running Docker container in foreground mode

When you run container without detach flag (-d) then you usually need to stop container when you want to close terminal or type another command. You can manipulate this with -a flag, but it’s easier just to run in detached mode.

Running Docker container in detached mode

When you run container in detached mode (with –detach, -d or -d=true flag) you can safely close terminal or type another command without affecting running containers, but in this mode by default you don’t see logs.

If you know your container name you can quickly run docker logs -f CONTAINER_NAME but when you don’t know it (which is often the case), then many people usually end up with this solution: quickly run docker ps, check container name, and quickly pass it to docker logs command. With terminal with poor autocompletion this takes long.

How to see docker logs from last ran container?

We usually don’t focus on Docker run output, which in detached mode is… container ID. So we don’t need to use Docker ps to check container name which just got started, we already have it’s ID, which can be used in Docker logs command as well. So we can copy and paste it after Docker run. Example:

$ docker run -d app
d6a2d30a9a85abf110192e944963bb0ce157dde143139c24abb4bbf038403451
$ docker logs -f d6a2d30a9a85abf110192e944963bb0ce157dde143139c24abb4bbf038403451

It’s already more convenient, but… better solution is to use it without need to do copy and paste. How? Simply use xargs to pass Docker run output (container id), to Docker logs. Example:

docker run -d app | xargs docker logs -f

And we have it :) Very simple, very convenient.

Why pass -f flag to Docker logs command?

In all previous examples I have passed -f flag to Docker logs command, which stand for follow. It’s not necessary, but without it Docker will only show already created logs. With follow option, it will show already created logs and will attach our terminal to see new logs, which is what we usually want, to monitor what is going on.

Summary

As Docker comes from Linux world it’s meant to be used from command line and is optimized for this. So having container ID returned from Docker run command (in detached mode) is probably meant to be passed to next command (or script), so we can safely use it to follow logs immediately.

Let me know in comment if you like this trick or share it with others with following buttons or direct url :)

tometchy

Tometchy

Passionate focused on agile software development and decentralized systems

Read More