Why Your Docker Containers Refuse to Die: The PID 1 Problem
Why Your Docker Containers Refuse to Die: The PID 1 Problem
You hit docker stop. Nothing happens. You wait ten seconds. Eventually Docker loses patience and sends SIGKILL. The container disappears, sure — but only after an annoying pause. Your CI pipeline feels slower than it should be, your Kubernetes pods take forever to shut down, and you get that nagging feeling something isn’t quite right.
I hit this exact issue last month while debugging a deployment that took 90 seconds just to roll out a single replica. Turned out to be the same boring culprit I’ve seen on at least four other projects: the PID 1 problem.
Let me walk you through what’s actually going on, why it trips up so many teams, and how to fix it cleanly.
The frustrating symptom
Here is what it usually looks like. You’ve got a Node app, a Python service, or whatever you’re running. You build it, start it, and try to stop it:
docker run --name myapp -d my-image:latest
# ... later ...
time docker stop myapp
# real 0m10.234s
Ten seconds. Every. Single. Time.
That 10 seconds is Docker’s default --time wait before it gives up and force-kills your container with SIGKILL. If you’re spinning up and tearing down dozens of containers in CI or production, those 10-second waits add up fast.
Even worse, in production it means your rolling deploys drag out, your zero-downtime story gets shaky, and any in-flight user requests get cut off mid-air because your app never got a chance to shut down nicely.
The root cause: PID 1 is weird
Here’s the part most tutorials skip.
In Linux, whichever process gets PID 1 has a special job. Normally, that’s the init system (like systemd) — the very first process that boots up the machine. Because it’s so important, the Linux kernel treats PID 1 differently from every other process in two big ways:
- It doesn’t get the usual default signal behavior.
Normally, if you send a polite “please stop” signal (SIGTERM) to a process, Linux stops it for you — even if the app didn’t write any shutdown code. Not for PID 1. If PID 1 doesn’t have an explicit handler forSIGTERM, the kernel quietly ignores the signal. It’s a safety guard so nobody accidentally kills the OSinitprocess. - It has to clean up zombie processes.
Whenever a process dies before its child processes finish, those leftover children get adopted by PID 1. When they finally exit, PID 1 is supposed to collect their exit status (by callingwait()). If it doesn’t, they hang around as<defunct>zombie processes forever.
Inside a Docker container, your app is PID 1.
So when you run docker stop, Docker sends SIGTERM to your app. If your Node or Python script didn’t explicitly listen for SIGTERM, the kernel silently drops it. Docker sits there waiting for 10 seconds, gives up, and nukes your container with SIGKILL.
flowchart LR
subgraph Broken ["Broken: App is PID 1 with no handler"]
direction TB
B1["1. You run docker stop<br/>Docker sends SIGTERM to PID 1"]
B2["2. Linux Kernel<br/>No handler found -> Signal is ignored"]
B3["3. Docker waits 10 seconds<br/>(30 seconds in Kubernetes)"]
B4["4. Docker sends SIGKILL<br/>App killed mid-request"]
B1 --> B2 --> B3 --> B4
end
subgraph Fixed ["Fixed: App handler or tini at PID 1"]
direction TB
F1["1. You run docker stop<br/>Docker sends SIGTERM to PID 1"]
F2["2. Handler or tini<br/>Catches or forwards SIGTERM"]
F3["3. App cleans up<br/>Finishes requests & closes DB pools"]
F4["4. Exits cleanly<br/>Container stops in under 1 second"]
F1 --> F2 --> F3 --> F4
end
style Broken fill:#0f172a,stroke:#ef4444,stroke-width:2px,color:#f8fafc
style B1 fill:#1e293b,stroke:#94a3b8,stroke-width:1.5px,color:#f8fafc
style B2 fill:#451a03,stroke:#f59e0b,stroke-width:1.5px,color:#f8fafc
style B3 fill:#450a0a,stroke:#f87171,stroke-width:1.5px,color:#f8fafc
style B4 fill:#7f1d1d,stroke:#ef4444,stroke-width:2px,color:#f8fafc
style Fixed fill:#0f172a,stroke:#10b981,stroke-width:2px,color:#f8fafc
style F1 fill:#1e293b,stroke:#94a3b8,stroke-width:1.5px,color:#f8fafc
style F2 fill:#1e1b4b,stroke:#818cf8,stroke-width:1.5px,color:#f8fafc
style F3 fill:#064e3b,stroke:#34d399,stroke-width:1.5px,color:#f8fafc
style F4 fill:#065f46,stroke:#10b981,stroke-width:2px,color:#f8fafc
Wait — why does
SIGKILLstill work after 10 seconds?
UnlikeSIGTERM,SIGKILLcan’t be caught or ignored, and Docker sends it from the host machine outside the container’s process space — so Linux lets it kill PID 1 right away.
You can confirm this is happening to your container in a few seconds:
docker exec myapp ps -ef
UID PID PPID CMD
root 1 0 node server.js
That 1 next to your app is the problem.
(Bonus tip: if you want to double-check whether PID 1 is actually listening for SIGTERM, run docker exec myapp grep SigCgt /proc/1/status. If it prints all zeros like 0000000000000000, your app isn’t catching any signals at all.)
The proof, in one tiny example
Let me show you the bug in the smallest possible repro. Save this as app.js:
// No SIGTERM handler
setInterval(() => {
console.log('alive');
}, 1000);
And a Dockerfile:
FROM node:20-alpine
COPY app.js /app.js
CMD ["node", "/app.js"]
Build, run, and time how long it takes to stop:
docker build -t pid1-demo .
docker run --name demo -d pid1-demo
time docker stop demo
# real 0m10.241s
docker rm demo
You’ll wait the full 10 seconds. Now compare that with this version of app.js:
// With a SIGTERM handler
process.on('SIGTERM', () => {
console.log('shutting down cleanly');
process.exit(0);
});
setInterval(() => {
console.log('alive');
}, 1000);
Rebuild and stop it again:
docker build -t pid1-demo .
docker run --name demo -d pid1-demo
time docker stop demo
# real 0m0.218s
docker rm demo
Instant. The container exits in well under a second because PID 1 now actually responds to SIGTERM.
Fix #1: Handle signals in your app
The cleanest fix is to handle SIGTERM (and usually SIGINT so Ctrl+C works locally too) right inside your application code. That’s the right place for it because your app probably has cleanup work to do anyway — finishing active HTTP requests, wrapping up database writes, or flushing logs.
Node.js HTTP server
const http = require('http');
const server = http.createServer((req, res) => {
res.end('ok');
});
server.listen(3000);
function shutdown() {
console.log('SIGTERM received, draining...');
// Stop taking new requests, finish the ones already in flight
server.close(() => process.exit(0));
// Optional (Node 18.2+): close idle keep-alive connections right away
if (typeof server.closeIdleConnections === 'function') {
server.closeIdleConnections();
}
// Hard stop if draining takes too long
setTimeout(() => process.exit(1), 8000).unref();
}
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
Heads-up on keep-alive connections: In Node.js,
server.close()waits for idle HTTP keep-alive connections to time out unless you callserver.closeIdleConnections()(added in Node 18.2). Without it, a browser or load balancer holding an idle socket can still slow down your shutdown.
Python scripts and web servers
If you’re running Python with Gunicorn or Uvicorn, good news — they already handle SIGTERM and drain workers for you out of the box (as long as they’re PID 1 and not stuck behind a shell).
For a plain Python script or background worker:
import signal
import sys
import time
def shutdown(signum, frame):
print("cleaning up...")
sys.exit(0)
signal.signal(signal.SIGTERM, shutdown)
signal.signal(signal.SIGINT, shutdown)
while True:
time.sleep(1)
What if your app expects a different signal? Some tools, like Nginx, prefer
SIGQUITto shut down gracefully instead ofSIGTERM. You can tell Docker which signal to send withSTOPSIGNAL SIGQUITin yourDockerfile.
Fix #2: Use a proper init process
Sometimes you can’t touch the application code, or you have a startup script that launches multiple child processes. In that case, put a tiny init process at PID 1 so your app sits at PID 2 and gets normal signal handling and automatic zombie cleanup.
The go-to tool for this is tini. It’s roughly 24 KB and does this one job really well.
Quick way: Docker’s --init flag
Docker actually ships with tini built in. Just pass --init when you run the container:
docker run --init --name demo -d pid1-demo
Or in docker-compose.yml:
services:
app:
image: pid1-demo
init: true
That’s it. Docker puts a small init binary at PID 1, your app becomes PID 2, signals get forwarded properly, and zombies get cleaned up automatically.
Better way: Bake tini into your image
The catch with --init is that people forget to pass the flag — and Kubernetes won’t pass it for you either. Baking tini straight into your Dockerfile guarantees it works everywhere.
On Alpine:
FROM node:20-alpine
RUN apk add --no-cache tini
COPY app.js /app.js
# tini becomes PID 1 and launches your app as a child
ENTRYPOINT ["/sbin/tini", "--"]
CMD ["node", "/app.js"]
On Debian / Ubuntu:
FROM python:3.12-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends tini \
&& rm -rf /var/lib/apt/lists/*
COPY worker.py /worker.py
ENTRYPOINT ["/usr/bin/tini", "--"]
CMD ["python", "/worker.py"]
There’s also dumb-init, which works very similarly (one minor difference is it forwards signals to the whole process group by default). Either one is a great choice.
The shell-form CMD trap
One more sneaky gotcha. Even if your app handles SIGTERM perfectly, writing your CMD or ENTRYPOINT in shell form breaks it:
# ❌ Shell form — PID 1 is /bin/sh, NOT node
CMD node /app.js
# ✅ Exec form — PID 1 is node
CMD ["node", "/app.js"]
When you write CMD node /app.js without brackets, Docker quietly wraps it in /bin/sh -c "node /app.js". That makes /bin/sh PID 1 instead of node. And /bin/sh doesn’t pass SIGTERM down to its child processes — so your app never even hears that Docker asked it to stop.
flowchart LR
subgraph ShellForm ["Shell Form: CMD node /app.js"]
direction TB
Sig1["docker stop sends SIGTERM"]
S1["PID 1: /bin/sh -c 'node /app.js'<br/>Swallows SIGTERM"]
S2["PID 2: node /app.js<br/>Never gets signal -> killed after 10s"]
Sig1 --> S1 --> S2
end
subgraph ExecForm ["Exec Form: CMD ['node', '/app.js']"]
direction TB
Sig2["docker stop sends SIGTERM"]
E1["PID 1: node /app.js<br/>App catches SIGTERM & stops cleanly"]
Sig2 --> E1
end
subgraph TiniForm ["With tini: ENTRYPOINT ['/sbin/tini', '--']"]
direction TB
Sig3["docker stop sends SIGTERM"]
T1["PID 1: /sbin/tini<br/>Forwards signal & reaps zombies"]
T2["PID 2: node /app.js<br/>Shuts down in under 1s"]
Sig3 --> T1 --> T2
end
style ShellForm fill:#0f172a,stroke:#ef4444,stroke-width:2px,color:#f8fafc
style Sig1 fill:#1e293b,stroke:#94a3b8,stroke-width:1.5px,color:#f8fafc
style S1 fill:#7f1d1d,stroke:#ef4444,stroke-width:1.5px,color:#f8fafc
style S2 fill:#450a0a,stroke:#f87171,stroke-width:1.5px,color:#f8fafc
style ExecForm fill:#0f172a,stroke:#38bdf8,stroke-width:2px,color:#f8fafc
style Sig2 fill:#1e293b,stroke:#94a3b8,stroke-width:1.5px,color:#f8fafc
style E1 fill:#0c4a6e,stroke:#38bdf8,stroke-width:1.5px,color:#f8fafc
style TiniForm fill:#0f172a,stroke:#10b981,stroke-width:2px,color:#f8fafc
style Sig3 fill:#1e293b,stroke:#94a3b8,stroke-width:1.5px,color:#f8fafc
style T1 fill:#1e1b4b,stroke:#818cf8,stroke-width:1.5px,color:#f8fafc
style T2 fill:#064e3b,stroke:#34d399,stroke-width:1.5px,color:#f8fafc
What if you actually need a shell?
Sometimes you genuinely need shell features — like expanding an environment variable ($PORT) or running a quick setup script before your app starts. In that case, always finish with exec:
CMD ["sh", "-c", "exec node /app.js --port ${PORT:-3000}"]
And if you’re using an entrypoint.sh script:
#!/bin/sh
set -e
# Run migrations or setup steps here...
# Replace the shell with your actual app
exec "$@"
exec swaps the shell process out and puts your app in its place, so the shell isn’t sitting in the middle blocking signals.
Quick cheat sheet: Which fix should you pick?
| Situation | Best Fix |
|---|---|
| You own the app code (API, worker, service) | Use exec-form CMD + handle SIGTERM / SIGINT in code |
| You can’t change the code, or it spawns child processes | Bake tini into the Dockerfile (or use --init / init: true) |
You need an entrypoint.sh script first |
Combine tini with exec "$@" at the end of the script |
You need env var expansion in CMD |
Wrap it with exec: CMD ["sh", "-c", "exec ..."] |
Prevention checklist
A few simple habits that have saved me hours of debugging:
- Default to exec-form
CMDandENTRYPOINT. It’s a one-line habit that prevents an entire class of shutdown bugs. - Bake
tiniin when you don’t control signal handling. Don’t count on everyone remembering--initat runtime. - Test shutdown locally with
time docker stop <container>. If an idle container takes more than a couple of seconds to stop, something is swallowingSIGTERM. Catch it on your laptop before it hits prod. - Tune
terminationGracePeriodSecondsin Kubernetes. Don’t just leave it at the 30-second default and hope — match it to how long your app actually needs to drain. - Log when
SIGTERMarrives. Add one log line when your shutdown handler runs. Next time a deploy looks slow in production, you’ll know right away whether the signal arrived or got silently dropped.
The meme version of this is: containers are easy, until they aren’t. The boring reality is that Linux process rules didn’t magically disappear just because we wrapped our apps in containers. PID 1 is special, signals are easy to drop, and zombies pile up if nobody reaps them. Once that clicks, half the weird container shutdown bugs you’ll ever run into stop being mysterious.