Enabling Python print statements in Docker detached container logs

Siraj
1 min readJan 22, 2024

--

Docker is used to run our application in a containerized fashion. Using one docker image we can have multiple instances of our same application.

When working with python and docker we might be able to notice that the print statements present in the code don’t get printed in the container logs, which might hinder the debugging process if we are using prints to test.

I’ll share how to use a command to enable the printing of python print statements.

instead of,

CMD ["python","main.py"]

Use unbuffered output with

CMD ["python","-u","main.py"]

To check the logs, run

docker logs container_id

Now both the stderr and stdout will be printed in the logs.

If for some reason the above doesn’t work, try setting the following environment variable “ENV PYTHONUNBUFFERED=1

For example,

docker run --name=my_app -e PYTHONUNBUFFERED=1 -d my_app_image_id

P.S: Logging can be used instead of print statements which will print directly without the need for -u or pythonunbuffered.

Thanks for reading!

--

--

Siraj
Siraj

No responses yet