bash script command "trap" doesn't work in docker container
<p>I'm trying to gracefully shutdown a service that I run in a docker container (on a raspberry pi 3 b running raspbian lite), since just issuing 'docker stop' breaks the service (a lock file does not get cleared)</p>

<p>My internet research has shown people working with the bash command 'trap' to execute a command when the script receives a signal to terminate.</p>

<p>I have tried this with the following:</p>

<pre><code>docker run --rm -it --name trap resin/rpi-raspbian:jessie /bin/bash -c " trap 'echo shutting down ; exit' INT; echo waiting; read"
</code></pre>

<p>When I run above command, 'waiting' is being printed to the screen and when i hit CTRL+C, the message 'shutting down' appears. - Exactly as I want it!</p>

<p>The only problem is, that I can't seem to get that signal sent to the bash script from outside the docker container. I've tried (in a parallel ssh session):</p>

<pre><code>docker kill --signal="INT" trap
docker kill --signal="SIGINT" trap
</code></pre>

<p>Furthermore, I tried to use the default signal that is being sent by 'docker stop', but that resulted in the console waiting ~10s (default docker stop timeout) and then killing the docker container.</p>

<pre><code>docker stop trap
</code></pre>

<p>Neither methods got the message 'shutting down' to print onto the screen.</p>

<p>I'd really appreciate any help.</p>

<p><strong>Edit 1:</strong>
It doesn't work with SIGTERM either (when I either of the following commands and then issue a 'docker stop' I still don't get the message 'shutting down').</p>

<pre><code>docker run --rm -it --name trap resin/rpi-raspbian:jessie /bin/bash -c " trap 'echo shutting down ; exit' TERM; echo waiting; read"
docker run --rm -it --name trap resin/rpi-raspbian:jessie /bin/bash -c " trap 'echo shutting down ; exit' SIGTERM; echo waiting; read"
</code></pre>

<p><strong>Workaround:</strong>
The image seems to be the problem. The entrypoint '/usr/bin/entry.sh' traps the signal. I've tried it with another image and it worked:</p>

<pre><code>$ docker run -it --name trap digitallyseamless/archlinux-armv6h /bin/bash -c " trap 'echo shutting down ; exit 0' SIGTERM; echo waiting; read"
</code></pre>

<p>Stop the container using (from another terminal)</p>

<pre><code>$ docker stop trap
</code></pre>

<p>Then view the container output</p>

<pre><code>$ docker logs trap
waiting
shutting down
</code></pre>

<p>As I have no particular need to use a specific image (it really is just a means to get me to my goal), I'll just swap out images.</p>

<p><strong>PS:</strong>
Huge thanks to @tkausl</p>