I have a simple script that prints hello every 2 seconds.
# entry.py
import time
while True:
print("hello")
time.sleep(2)
And I have an ultra-simple docker file that runs this script.
FROM python:3.9
COPY entry.py entry.py
CMD python entry.py
First I build the docker image:
$ docker build -t dtest .
Now I ran it with the -it
option, and it worked as expected.
$ docker run -it dtest
# hello printed to screen every two seconds
But when I run it in detached mode, and then try to see the logs, then I see nothing.
$ docker run -d dtest
e19f7285c098af582e163354be84774d1307b2409337cb03bdd217292899bdb7
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e19f7285c098 dtest "/bin/sh -c 'python …" 20 seconds ago Up 18 seconds epic_chatterjee
$ docker logs epic_chatterjee
# nothing is shown, exits
$ docker logs -f epic_chatterjee
# a cursor keeps blinking but nothing shown
It has to do with the way Python buffers output. Since writing to stdout is computationally expensive, it tries to gather large buffers and flushes them only occasionally if there is no terminal attached.
You could either change your Python code to:
Or run
python
with the-u
flag which forces unbuffered output