PYTHONUNBUFFERED
Docker
environment variables
container optimization
Python scripting

What does PYTHONUNBUFFERED=1 do in a Dockerfile?

Codemia Knowledge Hub ·

PYTHONUNBUFFERED=1 disables Python's output buffering, so print() statements and log messages show up in docker logs immediately instead of sitting in an internal buffer. Without it, you can wait minutes before seeing any output from a containerized Python process, which makes debugging and monitoring much harder.

Why Python buffers output in containers

Python has three I/O streams: stdout, stderr and stdin. When stdout is not connected to a terminal (a TTY), Python block-buffers it. Inside a Docker container stdout is almost never a TTY, so output accumulates in memory until the buffer fills (typically 8KB) or the process exits.

python
1# Without PYTHONUNBUFFERED, this output may not appear for minutes
2import time
3
4for i in range(10):
5    print(f"Processing batch {i}...")
6    time.sleep(30)
7
8# You might see all 10 lines dumped at once after 5 minutes

stderr is line-buffered (Python 3.9 and later), so errors and tracebacks appear almost immediately. stdout, which carries print() and most logging output, does not.

Setting PYTHONUNBUFFERED in a Dockerfile

Set the variable before any Python commands run:

dockerfile
1FROM python:3.12-slim
2
3# Force unbuffered stdout and stderr
4ENV PYTHONUNBUFFERED=1
5
6WORKDIR /app
7COPY requirements.txt .
8RUN pip install --no-cache-dir -r requirements.txt
9COPY . .
10
11CMD ["python", "app.py"]

If you don't control the Dockerfile, set it at runtime:

bash
docker run -e PYTHONUNBUFFERED=1 my-python-app

Or in docker-compose.yml:

yaml
1services:
2  worker:
3    image: my-python-app
4    environment:
5      - PYTHONUNBUFFERED=1

Any non-empty value works, such as 1 or true. An empty string (PYTHONUNBUFFERED=) does not enable unbuffered mode.

PYTHONUNBUFFERED vs. python -u

The -u flag has the same effect:

dockerfile
1# These two approaches are equivalent
2ENV PYTHONUNBUFFERED=1
3CMD ["python", "app.py"]
4
5# vs.
6CMD ["python", "-u", "app.py"]

The environment variable is usually preferred because it covers every Python process in the container, including subprocesses, scripts your application invokes and management commands. -u applies only to that one interpreter invocation.

When unbuffered output matters

Orchestration and log aggregation

Kubernetes, Docker Swarm, ECS and log aggregators (Fluentd, Logstash, CloudWatch) read container logs in real time via docker logs. Buffering creates a gap between when an event happens and when it shows up on your dashboard:

python
1import logging
2
3logging.basicConfig(level=logging.INFO)
4logger = logging.getLogger(__name__)
5
6# With PYTHONUNBUFFERED=1, this line appears in CloudWatch immediately
7logger.info("Payment processed for order %s", order_id)

Crash debugging

If the process crashes, unflushed output is lost for good. The last print statements before the crash never reach docker logs:

python
1print("Starting database migration...")      # May never appear
2print("Migrating table: users")              # May never appear
3perform_risky_migration()                     # Crashes here
4# Without PYTHONUNBUFFERED, you see nothing useful in the logs

Health checks and liveness probes

Kubernetes liveness probes and Docker health checks that watch log output need real-time data. Buffered output can make a healthy container look unresponsive.

Buffering options compared

ApproachScopeBuffering BehaviorBest For
Default (no setting)All streamsstdout block-buffered, stderr unbufferedBatch scripts with no monitoring
PYTHONUNBUFFERED=1All Python processes in containerBoth stdout and stderr unbufferedProduction containers, debugging
python -uSingle interpreterBoth stdout and stderr unbufferedQuick testing, one-off scripts
PYTHONDONTWRITEBYTECODE=1All Python processesUnrelated (prevents .pyc files)Often paired with PYTHONUNBUFFERED
flush=True in print()Single print callForces flush on that call onlySelective flushing in specific code paths

Production Dockerfile with PYTHONUNBUFFERED and PYTHONDONTWRITEBYTECODE

Most production Dockerfiles set both variables together:

dockerfile
1FROM python:3.12-slim
2
3# Prevent Python from writing .pyc files (smaller image, no stale bytecode)
4ENV PYTHONDONTWRITEBYTECODE=1
5# Force unbuffered output for real-time logging
6ENV PYTHONUNBUFFERED=1
7
8# Create non-root user for security
9RUN useradd --create-home appuser
10WORKDIR /home/appuser/app
11
12COPY requirements.txt .
13RUN pip install --no-cache-dir -r requirements.txt
14
15COPY . .
16USER appuser
17
18CMD ["python", "app.py"]

Mistakes with PYTHONUNBUFFERED

Leaving it out of the final stage of a multi-stage build. Environment variables from the builder stage don't carry over, so set it in the final stage:

dockerfile
1FROM python:3.12 AS builder
2COPY requirements.txt .
3RUN pip install --no-cache-dir -r requirements.txt
4
5FROM python:3.12-slim
6# Must set again in final stage
7ENV PYTHONUNBUFFERED=1
8COPY --from=builder /usr/local/lib/python3.12 /usr/local/lib/python3.12

Treating it as logging configuration. It does not configure the logging module. A handler with its own buffer (like MemoryHandler or a file handler with delayed flush) still needs separate configuration.

Expecting it to change stderr. stderr is already line-buffered, so there is little visible change there.

Ignoring overhead at high throughput. Unbuffered I/O makes each print() a system call instead of a memory write. For thousands of log lines per second, use the logging module with a StreamHandler and configured flush intervals instead of fully unbuffered output. For the vast majority of applications the cost is negligible and seeing logs in real time is well worth it.


Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design