Docker Stop and SIGTERM: Diagnose Graceful Shutdown Failures
Trace Docker stop signals through PID 1, exec-form entrypoints and application drain logic. Includes a tested Python worker and a container acceptance procedure.
When a container takes its entire stop timeout and then disappears, separate three questions: did the application receive the intended signal, did it stop accepting work, and did its remaining work finish before the deadline? Changing the timeout addresses only the last question. This guide follows that chain with a small Python worker, an exec-form Dockerfile, and an evidence-based container test. The worker was tested as a normal Linux process; Docker itself was unavailable in the test environment.
Follow the stop request through the process tree
Docker stop normally sends SIGTERM to the main process, waits for the configured grace period, and uses SIGKILL if the container still has not exited. The first signal can differ when the image or container specifies another stop signal. Read the effective configuration instead of assuming every image expects TERM. This guide concerns Linux containers; Windows process termination is a different investigation.
Think of the grace period as an outer budget. Inside that budget, the application may need to stop admission, finish or abandon an in-flight request, acknowledge durable work, close connections, and exit. Put timestamps around those phases. If the first application shutdown message never appears, adding time can merely make the same failure slower.
Keep the stopped container until you have collected its logs and state. Running the experiment with automatic removal can erase useful inspection evidence. Record the image identity, exact startup command, stop signal, timeout, and workload at the moment of stopping. A successful idle stop is weaker evidence than a successful stop during representative work.
Make the intended application receive the signal
Use JSON exec form for the main application command. A shell-form ENTRYPOINT introduces a shell between the container runtime and the program; the application may not receive the signal sent to the main process. Inspect the actual process tree, because startup scripts and runtime overrides can reintroduce that intermediate process even after the Dockerfile looks correct.
Exec form also changes argument handling: it does not provide shell variable expansion, pipes, or command chaining. Treat its array as executable arguments. If configuration needs shell preparation, use a short entrypoint script and replace that shell with the application using exec at the end. Avoid starting the application in the background and exiting the wrapper.
Here is an optional wrapper for the example worker. Use it instead of the direct Python ENTRYPOINT only when you actually need a preparation step. The quoted argument forwarding preserves separate arguments, including values containing spaces. A wrapper that remains alive must deliberately manage signal forwarding, child exit status, and reaping; that is a larger responsibility than this example needs.
#!/bin/sh
set -eu
# Perform only necessary, bounded preparation here.
exec python -u /app/worker.py "$@"Source: Docker: JSON arguments and operating-system signals ↗
A worker that finishes its current simulated unit
Save the following as worker.py. It installs TERM and INT handlers before announcing readiness. The handlers only request stopping; ordinary program flow prints progress and finishes the current simulated job. The loop checks the stop flag at its next job boundary. The ready and job-start messages let a test target an active worker rather than racing its startup.
This is a cooperative demonstration, not a queue consumer or an atomic job-admission protocol. Real systems must coordinate admission with shutdown, especially when work can arrive from another thread. The timed unit stands in for bounded work and performs no database transaction. A drain-complete message proves the example reached its exit path; it does not prove an external side effect became durable.
The accepted job duration is deliberately limited and rejects non-finite values. A production worker needs bounded database and network calls too: setting a stop flag cannot rescue an operation that never returns. Python handlers execute in the main interpreter thread, and some long-running native operations can delay their execution. Verify the behavior of the libraries that perform the actual work.
import argparse
import math
import os
import signal
import time
parser = argparse.ArgumentParser()
parser.add_argument("--job-seconds", type=float, default=2.0)
args = parser.parse_args()
if not math.isfinite(args.job_seconds) or not 0.05 <= args.job_seconds <= 30:
parser.error("job-seconds must be finite and between 0.05 and 30")
stopping = False
def request_stop(signum, frame):
global stopping
stopping = True
signal.signal(signal.SIGTERM, request_stop)
signal.signal(signal.SIGINT, request_stop)
print(f"ready pid={os.getpid()}", flush=True)
job = 0
while not stopping:
job += 1
print(f"job-start {job}", flush=True)
finish_at = time.monotonic() + args.job_seconds
while time.monotonic() < finish_at:
time.sleep(min(0.05, max(0, finish_at - time.monotonic())))
print(f"job-done {job}", flush=True)
print("drain-complete", flush=True)Source: Python 3.12: signal handlers and execution constraints ↗
Keep the container command explicit
Place this Dockerfile beside worker.py in a new lab directory. The entrypoint launches Python directly; CMD supplies replaceable arguments. STOPSIGNAL makes the expected request explicit. The unbuffered flag helps progress messages reach the log promptly, so missing output is less likely to be confused with a signal problem.
The base image tag is convenient for learning and can change over time. For a repeatable release, record or pin a verified base image digest through your normal build process. Do not copy an unverified digest from a tutorial. No image build or Docker runtime test was performed for this article; the Docker configuration is reviewed against the current official reference.
If you adopt the wrapper above, copy it into the image, make it executable, and change ENTRYPOINT to ["/app/entrypoint.sh"]. Keep CMD as the duration arguments. Do not retain both entrypoints and expect Docker to choose between them. Rebuild the image and verify the effective command for the container you actually created.
FROM python:3.12-slim
WORKDIR /app
COPY worker.py /app/worker.py
STOPSIGNAL SIGTERM
ENTRYPOINT ["python", "-u", "/app/worker.py"]
CMD ["--job-seconds", "2"]Test a busy stop and preserve the evidence
Use a disposable container name that is not already in use. Run the build and start commands below, then inspect logs until ready and at least one job-start appear. Issue stop while a job is in progress. With the two-second simulated unit and an eight-second budget, the expected result is that the current unit finishes, drain-complete appears, and the process exits normally.
The exact job number depends on when you stop it. Compare the last started and completed job rather than hard-coding job 1 in a human-driven test. Inspect the state and logs together. A zero exit code without the expected application evidence is inconclusive; a nonzero exit code requires investigation rather than automatically being labeled a signal-forwarding defect.
Repeat in a separate disposable container with a longer simulated unit and a deliberately shorter stop budget to exercise forced termination. Stop while that unit is still active. Expect no completed drain path when KILL interrupts it. Never run this failure injection against a real worker carrying uncommitted customer work. Remove the stopped lab container only after preserving the evidence you need.
docker build -t pwp-stop-lab .
docker run -d --name pwp-stop-lab pwp-stop-lab
docker logs pwp-stop-lab
# After observing an active job:
docker stop --timeout 8 pwp-stop-lab
docker logs pwp-stop-lab
docker inspect --format '{{json .State}}' pwp-stop-lab
# After reviewing evidence:
docker rm pwp-stop-labChoose a budget from the drain path
Estimate the longest allowed remaining work, then add bounded cleanup and a margin for scheduling and I/O. For example, a six-second remaining operation plus one second of cleanup and two seconds of margin suggests at least nine seconds for this particular envelope. Those are illustrative numbers, not a universal Docker recommendation. Measure under the actual load and resource limits.
An application deadline should leave room inside the container deadline. If the application abandons a unit only after the runtime has already killed it, its timeout cannot perform useful cleanup. Account for retry loops and connection timeouts: three consecutive waits can exceed the apparent timeout of any one call. Prefer a shared remaining budget over independent waits that each consume the full allowance.
Compose exposes a stop signal and stop_grace_period for the same operational concern. This example requests TERM and an eight-second interval for the lab. An explicit init process changes the process tree, so Python will no longer be PID 1 in that variant. Inspect the resulting arrangement and test it rather than treating a particular PID number as the success condition.
services:
worker:
build: .
init: true
stop_signal: SIGTERM
stop_grace_period: 8s
command: ["--job-seconds", "2"]Source: Docker Compose: service stop and init configuration ↗
Signal delivery and child reaping are different jobs
An application receiving TERM correctly can still mishandle child processes. If it launches subprocesses, decide who forwards termination, waits for them, collects exit status, and reaps finished children. Docker documents the init option as a lightweight way to handle init responsibilities. It does not implement your application-specific draining, transaction decisions, or queue acknowledgments.
Keep unrelated long-lived services in separate containers where practical. When a single service legitimately has multiple worker processes, use a process manager or lifecycle design that understands their relationship. A shell script that launches several background programs and waits for one exit is not automatically a complete shutdown policy.
For a real queue consumer, distinguish receiving a job from acknowledging it. If termination occurs after an external side effect but before acknowledgment, a retry can repeat that effect. Use the delivery system’s documented lease and acknowledgment rules and an appropriate idempotency design. A longer grace period reduces one source of interruption; it does not establish exactly-once processing.
Source: Docker: multiple processes and init responsibilities ↗
Match the observation to the next check
No shutdown evidence suggests checking the effective entrypoint, parent process, configured signal, and whether handlers were installed. A visible shutdown request followed by a timeout points toward blocking work, slow cleanup, or an insufficient budget. A fast exit with missing work points toward premature acknowledgment, background tasks that were never awaited, or cleanup that was assumed rather than observed.
Do not diagnose from exit code 137 alone. A KILL-related termination can have several causes; compare runtime state, OOM information, timestamps, and application logs. Conversely, a process can choose its own exit code. Preserve the causal evidence around the stop request rather than treating a familiar number as a complete explanation.
| Observation | Useful next evidence |
|---|---|
| Full timeout, no application drain message | Actual main process and stop signal |
| Drain starts, then forced exit | Remaining work and cleanup durations |
| Exit is fast, work is missing | Acknowledgment and child-task lifecycle |
| Different behavior after Compose change | Effective command, init and stop configuration |
What the local tests establish
The published Python worker was exercised as a normal Linux child process with TERM, INT, repeated TERM, several job durations, and a shell wrapper that execs the worker. The checks confirmed the started unit finished and the drain marker appeared before normal exit. A separate forced-KILL check confirmed the marker was absent. Invalid durations were rejected before readiness.
These checks do not establish container PID 1 behavior, Docker signal forwarding, Compose configuration validity at runtime, or durability of real work. Run the container acceptance procedure on your supported Docker version before adopting the pattern. Then replace the simulated unit with representative work and repeat during load, dependency delays, and process restarts.
The useful outcome is a traceable shutdown contract: the right process receives the right request, admission stops according to a defined policy, remaining work has a bounded outcome, and the runtime allows enough time for that outcome. Keep that contract in the release checks whenever startup commands, worker libraries, or deployment timeouts change.
Your next steps
- Trace signal delivery before extending the timeout.
- Exec-form startup and an explicit application drain path solve different parts of shutdown.
- Test active work and forced interruption; preserve logs, state and durability evidence.
Sources & official resources
Linked resources checked on 2026-10-28. Technical behavior and provider guidance can change; check the documentation for the version you use.
- Docker: container stop signal and timeout ↗
- Docker: JSON arguments and operating-system signals ↗
- Python 3.12: signal handlers and execution constraints ↗
- Dockerfile: ENTRYPOINT, CMD and STOPSIGNAL ↗
- Docker: inspect container state ↗
- Docker Compose: service stop and init configuration ↗
- Docker: multiple processes and init responsibilities ↗
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →