What is the use of PYTHONUNBUFFERED in docker file?

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:

Leave a Comment