Why doesn't my docker actually log anything?

11,458

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"]
Share:
11,458

Related videos on Youtube

Wayne Werner
Author by

Wayne Werner

I'm a husband to my beautiful wife, father to our children, Computer Science graduate from University of Central Arkansas. I love my wife, our children, computers, playing guitar (especially singing/playing for my wife and/or kids), bicycling (including taking my kids for rides in my bike trailer), woodworking, airbrushing, digital and traditional artistry, playing games with my family (traditional and digital), my poor Chevette that I had to sell, throwing knives, firearms, knot tying, rope making, whip making, and really just learning new stuff in general. If I don't know about it I probably want to learn about it, if only so I can make informed decisions about it. My three favorite programming languages are Python, Lisp, and Assembly (though I'm not sure about the order of those last two languages...). I think the CANSPAM act is one of the dumbest pieces of legislation in the history of the universe I love Python and HTML+Javascript. I'm #SOreadytohelp (I really want a t-shirt, what can I say?)

Updated on September 18, 2022

Comments

  • Wayne Werner
    Wayne Werner over 1 year

    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.

    • BMitch
      BMitch over 5 years
      Check if it's IO buffering: stackoverflow.com/q/107705/596285
    • Wayne Werner
      Wayne Werner over 5 years
      @BMitch that was it, thanks! I spent a couple of hours last night fighting this darn thing.
  • Wayne Werner
    Wayne Werner over 5 years
    Because I was using another command (i.e. waitress-serve in my case), so I added ENV PYTHONUNBUFFERED definitely to my Dockerfile (it could be any non-empty string, FWIW)