Orchestrators such as Kubernetes send SIGTERM and wait a grace period before SIGKILL, so the service should catch SIGTERM, stop accepting new requests, finish in-flight work, flush logs and close connections, then exit.
In containers the main process is PID 1, which does not get default signal handlers, so the application must handle SIGTERM explicitly (or run under a small init process) and should reap child processes.
import signal, sys
shutting_down = False
def handle_sigterm(signum, frame):
global shutting_down
shutting_down = True # stop accepting new work; let the loop drain and exit
signal.signal(signal.SIGTERM, handle_sigterm)