14.1.2.4 Production Graceful Shutdown
A focused guide to Production Graceful Shutdown, connecting core concepts with practical Docker and container operations.
Production graceful shutdown ensures an application correctly handles a termination signal by finishing in-flight work and cleanly releasing resources before actually exiting, rather than being abruptly killed mid-request, an important behavior for avoiding dropped requests during routine restarts, deployments, or scaling events.
Why Docker Sends a Termination Signal Before Killing a Container
Docker's default stop behavior sends SIGTERM, giving the application a window of time to shut down cleanly, before eventually sending a more forceful SIGKILL if it hasn't exited within that window.
docker stop --time=30 myapp
This gives the application up to thirty seconds to handle SIGTERM and shut down gracefully before being forcefully killed.
Implementing Graceful Shutdown Handling in the Application
The application itself needs to explicitly listen for this signal and respond appropriately, finishing active requests rather than dropping them immediately.
process.on('SIGTERM', async () => {
server.close(() => {
db.disconnect();
process.exit(0);
});
});
This stops accepting new connections, allows in-flight requests to complete, then cleanly disconnects from the database before actually exiting.
Why PID 1 Signal Handling Requires Specific Attention
A process running as PID 1 inside a container doesn't receive default signal handling behavior the way a normal process would — an application needs to explicitly handle this, or use an init process designed to forward signals correctly.
ENTRYPOINT ["dumb-init", "node", "server.js"]
A lightweight init wrapper like this correctly forwards signals to the actual application process, working around this PID 1-specific behavior.
Verifying Graceful Shutdown Actually Works
Testing that an in-flight request genuinely completes before the container fully stops validates this behavior in practice.
curl http://localhost:8080/slow-endpoint & docker stop myapp
Why Production Graceful Shutdown Matters
Properly implemented graceful shutdown handling prevents dropped requests and data inconsistency during routine, expected events like deployments and scaling, a behavior that's easy to overlook but important for a genuinely production-quality application.