Interview Prep/Build Tools (Java, Node.js, Python, .NET)/Python builds (pip, venv, requirements.txt)

Why is PYTHONUNBUFFERED=1 set in Docker images?

IntermediateConceptPython builds (pip, venv, requirements.txt)
Answer

Short answer

By default, Python buffers standard output when it isn't writing to a terminal — prints are held in memory and written in chunks. In containers that means logs appear late, or are lost entirely if the container crashes. PYTHONUNBUFFERED=1 makes Python write output immediately, so docker logs and kubectl logs show everything in real time.

Example

ENV PYTHONUNBUFFERED=1

Equivalent: run python -u app.py.

Symptom without it

"The pod crashed but kubectl logs shows nothing" — the last lines were still in the buffer when the process died.

Related

PYTHONDONTWRITEBYTECODE=1 stops Python writing .pyc files — slightly smaller, cleaner images.

What to say in the interview

"It disables output buffering so logs reach stdout immediately — essential when logs are collected from container stdout, especially to see the last lines before a crash."

All Build Tools (Java, Node.js, Python, .NET) questions Roadmap: Python apps: pip, venv & requirements.txt

More on Python builds (pip, venv, requirements.txt)