SoFunction
Updated on 2025-03-10

How to solve the problem that docker logs cannot output the content printed in real time

docker logs cannot output script print content in real time

Background & Questions

I added a line of commands to run python scripts after the command parameter:

command:python 

Then this command will start running when the container is generated.

However, when viewing the logs through the docker logs -f command, I found that the things printed through print in the py script will not be displayed in real time, but will only be displayed after the program is executed. This is not the result I want.

But if you enter the container to manually execute the python script, you can print it in real time.

solve

After searching for information online, I found that in this case, python will buffer its output by default, so if you want unbuffered output, then add a "-u" parameter:

command: python -u 

At this time, when you view the logs through docker logs -f, you will see the results printed in real time

Problem solved!

docker logs does not print python program output

docker logs --tail 50 --follow a8

Even if the container is running normally, there will be no output to print it out, and it will be useless to wait, and it will be printed once or twice from time to time. Finally, I found out that it was the IO of Python that was buffered, and stdout blocked it.

Just modify print(flush=True) in the python code. If you use gunicorn or logging, you need to reconfigure it.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.