In this lesson, you will learn how to configure your containers to handle shutdown signals so that your applications close connections and save data without interruption.
Why Shutdowns Need "Grace"
When you stop a container or deploy an update, Docker sends a SIGTERM signal to your application. By default, many applications (or the shell scripts wrapping them) might ignore this or force-close immediately. If your app is in the middle of writing to a database or streaming a file, an abrupt exit can lead to corrupted data or lost requests.
A graceful shutdown means your application catches the SIGTERM signal, stops accepting new work, finishes current tasks, and safely closes database connections before exiting.
Implementing Signal Handling
To ensure your container responds correctly, you must run your process as PID 1 in the container. Avoid using shell scripts to start your app unless you use the exec command, which replaces the shell process with your application.
For example, in a Dockerfile, prefer the exec form:
# GOOD: The app receives the signal directly as PID 1
CMD ["node", "server.js"]
# BAD: The shell process becomes PID 1 and often swallows signals
CMD npm start
Once your application receives the SIGTERM, you should implement a listener in your code. In a Node.js application, it looks like this:
process.on('SIGTERM', () => {
console.log('Shutdown signal received: closing connections...');
server.close(() => {
console.log('HTTP server closed.');
db.disconnect(); // Ensure data is saved
process.exit(0);
});
});
Docker's Timeout
Docker allows your container a "grace period" to perform these tasks. By default, it waits 10 seconds after sending SIGTERM before sending a SIGKILL (which forces the process to stop immediately). If your application requires more time to flush logs or finish heavy write operations, you can increase this timeout during deployment:
docker stop --time=30 my-container
If you are using docker-compose, you can define this in your configuration:
services:
web:
image: my-app
stop_grace_period: 30s
By ensuring your app listens for the signal and providing enough time for it to clean up, you prevent data loss and ensure a smooth user experience during your CI/CD service updates.
Key Takeaway: A graceful shutdown happens when your application PID 1 catches the SIGTERM signal and completes pending tasks before exiting, supported by a properly configured stop_grace_period.