DEV Community

Cover image for 3 Silent Traps When Running Python Scripts in Docker
Tino K.
Tino K.

Posted on Edited on

3 Silent Traps When Running Python Scripts in Docker

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:

  1. docker logs shows nothing until the script finishes (or crashes).
  2. Running docker stop hangs for exactly 10 seconds every single time.
  3. The container runs as root and 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
Enter fullscreen mode Exit fullscreen mode

(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
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
hritik_chaudhary_5db0056f profile image
Hritik Chaudhary •

Useful template. One catch on trap 2: exec form makes your script PID 1, but the kernel only delivers a signal to PID 1 if the process has installed a handler for it. A Python script with no signal.signal(SIGTERM, ...) as PID 1 still sits there until Docker's SIGKILL at 10 seconds. So the handler in your snippet is what actually fixes it, and I would call it required. Running with docker run --init (init: true in compose) gives you tini as PID 1, which forwards signals and reaps zombies too.

On trap 3: useradd without a fixed UID gives you 1000 on most images, which only matches the host user by luck. For bind mounts, passing --user "$(id -u):$(id -g)" at run time, or a build arg for the UID, avoids root-owned files in both directions.