Graceful Container Shutdown
Ensuring a graceful shutdown of a Docker container is crucial for maintaining the integrity of your application and the data it manages. When a container is stopped, the main process running inside the container should be given the opportunity to perform any necessary cleanup tasks, such as saving data, closing connections, or releasing resources.
Handling SIGTERM Signals
By default, when a Docker container is stopped, the main process running inside the container receives a SIGTERM
signal. This signal is used to request a graceful shutdown of the process. To ensure a proper shutdown, your application should be designed to handle the SIGTERM
signal and perform the necessary cleanup tasks before exiting.
Here's an example of how you can handle the SIGTERM
signal in a Python application:
import signal
import time
def graceful_shutdown(signum, frame):
print("Received SIGTERM, performing graceful shutdown...")
## Perform cleanup tasks here
time.sleep(5) ## Simulating cleanup tasks
print("Graceful shutdown complete.")
exit(0)
signal.signal(signal.SIGTERM, graceful_shutdown)
## Main application logic
while True:
print("Application running...")
time.sleep(1)
In this example, the graceful_shutdown
function is registered as the handler for the SIGTERM
signal. When the container is stopped, this function will be called, allowing the application to perform any necessary cleanup tasks before exiting.
Customizing the Shutdown Timeout
By default, Docker will wait 10 seconds for the main process to exit after receiving the SIGTERM
signal. If the process does not exit within this timeout, Docker will send a SIGKILL
signal, which forcefully terminates the process.
You can customize the shutdown timeout by using the --stop-timeout
flag when starting a Docker container:
docker run -d --stop-timeout 20 your-image
This will increase the shutdown timeout to 20 seconds, giving the main process more time to perform a graceful shutdown.
Using Process Managers
Another approach to ensure a graceful shutdown is to use a process manager, such as tini
or dumb-init
, as the container's entrypoint. These process managers are designed to handle signals and forward them to the main process, ensuring a proper shutdown sequence.
## Example of using tini as the entrypoint for a Docker container
ENTRYPOINT ["/usr/bin/tini", "--", "your-application-command"]
By using a process manager, you can simplify the signal handling in your application and rely on the process manager to handle the shutdown process on your behalf.
By understanding and implementing graceful shutdown mechanisms, you can ensure that your Docker containers can be stopped and restarted safely, without losing data or encountering other issues.