What is STOPSIGNAL in Dockerfile and How to Use It
STOPSIGNAL instruction in a Dockerfile sets the system signal that Docker sends to stop a container. It tells Docker which signal to use to gracefully terminate the main process inside the container when stopping it.How It Works
When you stop a Docker container, Docker sends a signal to the main process inside that container to tell it to stop. By default, this signal is SIGTERM, which politely asks the process to shut down.
The STOPSIGNAL instruction lets you change this default signal to another one, like SIGINT or SIGQUIT. Think of it like telling a friend how you prefer to be asked to stop doing something—some signals are gentler, some are more forceful.
This helps when your application inside the container listens for a specific signal to clean up resources or save data before exiting. Setting the right stop signal ensures your app shuts down smoothly without losing data or leaving things messy.
Example
This example shows a Dockerfile that sets the stop signal to SIGINT. When you stop the container, Docker sends SIGINT instead of the default SIGTERM.
FROM alpine:latest STOPSIGNAL SIGINT CMD ["sh", "-c", "trap 'echo Received SIGINT; exit 0' INT; while true; do sleep 1; done"]
When to Use
Use STOPSIGNAL when your application needs a specific signal to shut down properly. For example, some apps listen for SIGINT (like pressing Ctrl+C) to save data or close connections gracefully.
If you don’t set STOPSIGNAL, Docker uses SIGTERM by default, which might not trigger your app’s cleanup code. Setting the right stop signal helps avoid data loss and keeps your app healthy.
Real-world cases include databases, web servers, or any service that needs time to finish tasks before stopping.
Key Points
- STOPSIGNAL changes the signal Docker sends to stop a container.
- Default signal is
SIGTERM, but you can set others likeSIGINTorSIGQUIT. - Helps your app shut down cleanly by catching the right signal.
- Useful for apps that need to save state or close resources before exit.