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.
- [Django]-Django: remove a filter condition from a queryset
- [Django]-Getting Values of QuerySet in Django
- [Django]-How to get getting base_url in django template
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.
- [Django]-Django annotation with nested filter
- [Django]-What is the purpose of adding to INSTALLED_APPS in Django?
- [Django]-Warning: Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'