I’ve refered the Trapping signals in Docker containers, and the offical blogs about stop and kill.
how stop and kill works
stop: The main process inside the container will receive SIGTERM, and after a grace period, SIGKILL. The first signal can be changed with the STOPSIGNAL instruction in the container’s Dockerfile, or the –stop-signal option to docker run.
kill: The main process inside the container is sent SIGKILL signal (default), or the signal that is specified with the –signal option. You can reference a container by its ID, ID-prefix, or name. When you want to send SIGHUP, there is the command
docker kill --signal=SIGHUP my_container
.
Why bothers?
You may notice that The main process inside the container
in both descriptions. What if we have
multiprocess in the container?
Let’s create a container
1 | // main.js |
1 |
|
1 | FROM node:10.17.0-alpine |
We could exec to watch the process.
1 | docker exec -ti my-kill /bin/sh |
We can get different results if we modify the entrypoint:
1 | # Use `ENTRYPOINT ["node", "main.js"]` |
1 | # Use `ENTRYPOINT ["/run.sh"]` |
When we use
ENTRYPOINT ["node", "main.js"]
, thenode
process will receive the SIGTERM signal and close itself.
When we use
ENTRYPOINT ["/run.sh"]
, thenode
process doesn’t get the proper signal, and it was forcibly shut down.
How to close the container gracefully
Well, we know what the offical description really means. It will only send SIGTERM
to the main process. If we have to use the script, we need to pass the signal to the child process.
Using trap
to enhance shell scripts
Copy from program.sh(One one process):
1 |
|
Use supervisor or S6
Please refer to S6.
Conclution
I want you to know that Docker doesn’t expected to run multiple processes within a single container, and I don’t encourage reader to write some weird scripts.
If you really need multiprocess support, please consider to use Kubernetes
or Docker Dompose
.