Course contentsShow
← Linux
Lesson 1587 of 1,81913. Containerization Primitives and NamespacesFree lesson

Graceful Shutdown and Signal Propagation

Ensure that signals sent to containers are correctly translated and propagated to the entrypoint process.

In this lesson, you will learn how signals are translated across namespace boundaries to ensure your containerized applications exit cleanly without data corruption.

When a container orchestrator (like containerd or CRI-O) decides to stop a container, it sends a SIGTERM signal to the container's init process. The challenge lies in the "PID 1" problem: in Linux, PID 1 is special. It does not handle signals by default unless it is explicitly programmed to do so. If your application entrypoint is a shell script or a poorly configured binary, it often ignores these signals, forcing the runtime to wait for a timeout and eventually resort to a forceful SIGKILL.

The Signal Translation Chain

Signals are namespace-aware. When the host runtime sends a signal, it target the PID within the container's PID namespace. For the propagation to work, the process inside the container must be PID 1. If you launch your app using a shell (e.g., CMD ["/bin/sh", "-c", "my-app"]), the shell becomes PID 1. Most shells do not forward signals to their children by default. Consequently, your actual application (my-app) never receives the SIGTERM needed to flush logs, close database connections, or finish processing requests.

Achieving Proper Propagation

To fix this, you must ensure your application receives the signal directly as PID 1 or uses an exec form that replaces the shell process:

# Incorrect: shell prevents signal propagation
ENTRYPOINT ["/bin/sh", "-c", "myapp"]

# Correct: the shell is replaced, making myapp the PID 1 process
ENTRYPOINT ["/usr/bin/myapp"]

If you must use a wrapper script, you should use the exec command to hand over the PID 1 role:

#!/bin/sh
# Prepare environment...
exec /usr/bin/myapp

When exec is used, the shell process is replaced by myapp. Because myapp is now the process with PID 1 in the container's namespace, the runtime’s SIGTERM lands directly on the application, allowing it to perform a graceful shutdown.

Key Takeaway: To ensure graceful shutdowns, your container entrypoint must be the process that holds PID 1, or it must be explicitly configured to forward signals to its child processes.