3 Silent Traps When Running Python Scripts in Docker
If you wrap a Python worker or cron script in a quick Dockerfile, it will usually run fine on your laptop.
Then you deploy it to a VPS, and three annoying things happen:
-
docker logsshows nothing until the script finishes (or crashes). - Running
docker stophangs for exactly 10 seconds every single time. - The container runs as
rootand leaves root-owned files in your mounted volumes.
None of these throw an error. Here is why they happen and the exact Dockerfile changes that fix them.
Trap 1: Your print() Logs Disappear
You run a long-running Python script inside a container, run docker logs -f my-worker, and stare at an empty terminal. The script is running, CPU usage is up, but there is zero output.
Why it happens:
Python buffers stdout when it detects that it isn't attached to an interactive terminal (TTY). Inside Docker, stdout is piped, so Python holds onto your logs in memory in 4KB–8KB chunks until the buffer fills up or the process exits. If your script crashes before flushing, you lose the last few minutes of logs completely.
The Fix:
Set PYTHONUNBUFFERED=1 in your Dockerfile (or pass -u to python).
ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 (Bonus: PYTHONDONTWRITEBYTECODE=1 stops Python from writing useless .pyc files inside ephemeral containers.)
Trap 2: docker stop Always Takes 10 Seconds
When you run docker stop, Docker sends a SIGTERM signal to PID 1 inside the container so your script can clean up (close DB connections, flush files). If the process doesn't exit within 10 seconds, Docker gives up and sends SIGKILL.
If your container always hangs for 10 seconds before stopping, your Python script isn't receiving SIGTERM at all.
Why it happens:
Using the "shell form" of CMD in your Dockerfile:
# BAD: Spawns /bin/sh as PID 1. Shell ignores SIGTERM and doesn't forward it to Python. CMD python worker.py When you omit the brackets, Docker wraps your command in /bin/sh -c "python worker.py". The shell becomes PID 1, eats the SIGTERM, and your Python process never knows it was asked to shut down.
The Fix:
Always use the JSON "exec form" (CMD ["...", "..."]) so Python itself runs as PID 1 and handles signals directly:
# GOOD: Python runs as PID 1 and receives SIGTERM immediately CMD ["python", "worker.py"] If you want to handle graceful shutdown cleanly inside your Python script, catch SIGTERM:
import signal import sys import time running = True def handle_sigterm(signum, frame): global running print("SIGTERM received. Finishing current task and exiting...") running = False signal.signal(signal.SIGTERM, handle_sigterm) while running: # Do work here time.sleep(1) print("Clean exit.") sys.exit(0) Trap 3: Running as root by Default
By default, every process inside a Docker container runs as root (UID 0).
If your Python script writes output CSVs, SQLite databases, or logs to a bind-mounted host directory (-v ./data:/app/data), those files will be owned by root on your host machine. Next time your host user or CI script tries to read or delete them, you hit PermissionError.
The Fix:
Create a dedicated non-root user in the Dockerfile and switch to it before CMD:
RUN useradd --create-home --shell /bin/bash appuser USER appuser Copy-Paste Production Dockerfile
Putting all three fixes together, here is the minimal template I use for Python workers, scrapers, and automation jobs:
FROM python:3.12-slim # 1. Disable stdout buffering & .pyc generation ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 WORKDIR /app # 2. Install dependencies before copying code (better layer caching) COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt # 3. Create non-root user RUN useradd --create-home --shell /bin/bash appuser COPY --chown=appuser:appuser . . USER appuser # 4. Use exec form so Python receives SIGTERM CMD ["python", "worker.py"] It adds zero external dependencies, cuts out the 10-second shutdown delay, keeps host volume permissions clean, and ensures logs show up in real time.
