Why doesn't my docker actually log anything?

I have the following python file:

 import time
 from datetime import datetime


 while True:
     time.sleep(1)
     print(datetime.now())

I've added it to a Dockerfile:

FROM python:3.7


WORKDIR /test
COPY test.py /test/
CMD ["python", "test.py"]

If I build this and run with

sudo docker run -it --name test myimage

everything is awesome. Every second or so it prints the current time.

On the other hand, if I run it with:

sudo docker run -d --name test myimage

It runs off into the background, but if I do...

sudo docker logs test

I get nothing! Not a darn thing.

Any clue why this is happening, or how I could figure it out? Both when I'm using -d and not when I run docker inspect it gives me "Type": "json-file", "Config": {}

I'm runing Docker 18.06.1-ce, build e68fc7a, on Ubuntu 18.04.


Solution 1:

Without a tty attached, python is likely buffering stdout. There are lots of ways to solve this, including adding this change to your script:

print(datetime.now(), flush=True)

Or without changing your script, you can run stdbuf to turn off output buffering:

CMD ["stdbuf", "-oL", "python", "test.py"]