Mittenchops
Mittenchops

Reputation: 19694

View stdout and logs of an ephemeral docker container

I understand there are many questions about how to read docker logs that are answered by:

$ docker logs containername

However, I am working with an ephemeral container, one created with -rm, so I do not have time to call logs after creating it. But I am still interested in seeing the logs of how it ran.

My command is:

docker run --name myname --rm  python-my-script:3.7.4 - --myflags "myargs"

Now, I'd like to see how my script runs with these arguments. My entrypoint has a script that should effectively be reading in and printing "myargs" to the console.

But when I do:

docker logs myname
Error: No such container: myname

Or if I'm really quick:

Error response from daemon: can not get logs from container which is dead or marked for removal

How can I see the logs of a container that is no longer running? I'd prefer not to install something heavyweight like syslog.

Upvotes: 4

Views: 1777

Answers (1)

atline
atline

Reputation: 31654

The default logging driver for Docker is json-file, which you are able to use docker logs to see it. But if you delete the container or use --rm when run the container, the logs will be deleted after the container removed.

For you case, you need change a logging driver to assure the log still could be seen even after the container deleted.

There are a lots of logging driver which could meet your requirements, see this. E.g fluentd, splunk, etc.

Here, give a simplest way to reserve the log, use journald, a minimal example for your reference:

  1. Start the container with journald log driver, need to set a container name which will be used later to retrieve the log:

    $ docker run --log-driver=journald --rm --name=trial alpine echo "hello world"
    
  2. After the container finish print "hello world", the container will be deleted as it specify --rm, check if docker logs ok:

    $ docker logs trial
    Error: No such container: trial
    
  3. Use journald to if we can get the log:

    $ journalctl CONTAINER_NAME=trial --all
    -- Logs begin at Mon 2018-12-17 21:35:55 CST, end at Mon 2019-08-05 14:21:19 CST. --
    Aug 05 14:18:26 shubuntu1 a475febe91c1[1975]: hello world
    

You can see you can use journalctl to get the log content "hello world" even the container was removed.

BTW, if you do not want to specify --log-driver every time you start a container, you can also set it as default log driver in daemon.json, see this:

{
  "log-driver": "journald"
}

Meanwhile, you still can use docker logs to get the logs if the container not deleted.

Upvotes: 4

Related Questions