Graceful Shutdown of Docker Containers
Gracefully shutting down Docker containers is an important aspect of container management, as it ensures that the application inside the container can perform any necessary cleanup tasks before terminating. This helps to prevent data loss, maintain application state, and ensure a smooth transition when stopping or restarting a container.
Handling the SIGTERM Signal
When you issue the docker stop
command, Docker sends a SIGTERM
signal to the main process running inside the container. This signal is the default way for Docker to request the container to stop. The application running inside the container should be designed to handle the SIGTERM
signal and perform any necessary cleanup tasks, such as saving data, closing connections, or flushing caches.
## Stop a Docker container gracefully
docker stop my-container
Configuring the Stop Timeout
By default, Docker waits for 10 seconds after sending the SIGTERM
signal before sending a SIGKILL
signal, which forcefully terminates the container. If the application inside the container does not respond to the SIGTERM
signal within the 10-second timeout, Docker will kill the container.
You can customize the stop timeout by using the --stop-timeout
flag when stopping a container:
## Stop a Docker container with a custom timeout
docker stop --time=30 my-container
In this example, Docker will wait for 30 seconds before sending the SIGKILL
signal.
Implementing Graceful Shutdown in Applications
To ensure a graceful shutdown of your Docker containers, it's important to design your applications to handle the SIGTERM
signal properly. This typically involves implementing signal handlers in your application code that perform the necessary cleanup tasks when the SIGTERM
signal is received.
Here's an example of how you might implement graceful shutdown in a simple Node.js application:
// app.js
const http = require("http");
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Hello, World!\n");
});
// Handle the SIGTERM signal
process.on("SIGTERM", () => {
console.log("Received SIGTERM signal, shutting down gracefully...");
server.close(() => {
console.log("Server closed, exiting process.");
process.exit(0);
});
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000/");
});
By properly handling the SIGTERM
signal and performing any necessary cleanup tasks, you can ensure that your Docker containers are shut down gracefully, preventing data loss and maintaining application state.