[Django]-What is the use of PYTHONUNBUFFERED in docker file?

411👍

Setting PYTHONUNBUFFERED to a non-empty value different from 0 ensures that the python output i.e. the stdout and stderr streams are sent straight to terminal (e.g. your container log) without being first buffered and that you can see the output of your application (e.g. django logs) in real time.

This also ensures that no partial output is held in a buffer somewhere and never written in case the python application crashes.

Since this has been mentioned in several comments and supplementary answers, note that PYTHONUNBUFFERED has absolutely no influence on the input (i.e. the stdin stream).

In other words, turning off buffering to stdout/stderr in a docker container is mainly a concern of getting as much information from your running application as fast as possible in the container log and not loosing anything in case of a crash.

Note that turning buffering off can have an impact on performance depending on your hardware/environment. Meanwhile it should be minor in most situations (unless you have slow disks or are writing a tremendous amount of logs or had the bad idea to configure your docker daemon to write your logs on a slow network drive…). If this is a concern, buffering can be left on and you can flush the buffer directly from your application when needed. See link [4] below on this subject.

References:

16👍

A PYTHONUNBUFFERED non-empty value forces the stdout and stderr streams to be unbuffered. This option has no effect on the stdin stream.

6👍

This instructs Python to run in UNBUFFERED mode, which is recommended when using Python inside a Docker container. The reason for this is that it does not allow Python to buffer outputs; instead, it prints output directly, avoiding some complications in the docker image when running your Python application.

Leave a comment