The Python Oracle

`Docker logs` erroneously appears empty until container stops

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Quiet Intelligence

--

Chapters
00:00 `Docker Logs` Erroneously Appears Empty Until Container Stops
00:43 Accepted Answer Score 8
01:19 Thank you

--

Full question
https://stackoverflow.com/questions/5870...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #docker

#avk47



ACCEPTED ANSWER

Score 8


This might be happening because stdout and stderr are buffered streams.

When interactive, stdout and stderr streams are line-buffered. Otherwise, they are block-buffered like regular text files. You can override this value with the -u command-line option.

Try adding the -u flag.

CMD [ "python", "-u", "./your_script.py" ]

Or, as pointed out by David Maze, you could set the PYTHONUNBUFFERED environment variable and achieve the same result.

ENV PYTHONUNBUFFERED=1

You could also flush stdout everytime you call print().

sys.stdout.flush()

Alternatively, see the logging module.