<p>TL; DR: how should I write a <code>Dockerfile</code> or docker commands to run docker containers so that I can stop and exit the running docker container when I hit <code>ctrl+c</code>?</p>

<hr>

<h3>Background</h3>

<p>I need to run an infinite while loop in shell script. When I ran this script locally, the <code>ctrl+c</code> command will exit the infinite loop.</p>

<pre><code># content of sync.sh

while true; do
  echo "Do something!"
  some_syncing_command || {
    rm -rf /tmp/healthy &amp;&amp; break
  }
  echo "Finish doing something!"
  touch /tmp/healthy
  sleep ${waitingSeconds}
done
</code></pre>

<p>So based on the shell script, I then created a Docker Image with the following <code>Dockerfile</code> content:</p>

<pre><code>FROM debian:stretch 
COPY sync.sh .

ENTRYPOINT ["/sync.sh"]
</code></pre>

<p>and build the image by running <code>docker build -t infinite-loop .</code></p>

<h3>Problem</h3>

<p>However, after trying different attempts to run the <code>infinite-loop</code> image, I cannot stop and exit the running docker container after hitting <code>ctrl + c</code>. Here are the docker commands I used to run the docker image:</p>

<ol>
<li><code>docker run --rm to-infinity-1 infinite-loop</code></li>
<li><code>docker run --rm -it to-infinity-2 infinite-loop</code></li>
<li><code>docker run --rm -d to-infinity-3 infinite-loop</code>, then run <code>docker attach</code> on <code>to-infinity-3</code></li>
</ol>

<p>All of the above commands fail to stop and exit the infinite loop after executing <code>ctrl+c</code> directly. Hence I need to run <code>docker stop [container-name]</code> to stop the running containers of infinite loops. What should I change in my implementation to resolve this problem?</p>

<p>Thank you.</p>

<p><strong>Edit:</strong> additional context, I am using kubernetes with the infinite loop container. I wonder if this <code>ctrl+c</code> problem (related to SIGINT) will interfere with kubernetes if I want to gracefully stop and exit the running pod. Note that although the <code>ctrl+c</code> is problematic, I was still able to use <code>docker stop</code> to stop the running containers.</p>

<p><strong>“docker run” traps or ignores ctrl+c.</strong></p>

<p>If you don’t want to lose your shell you can trying stopping the container from another terminal on the same docker host.</p>

<p>Open a new shell and execute</p>

<pre><code>$ docker ps # get the id of the running container
$ docker stop &lt;container&gt; # kill it (gracefully)
</code></pre>

<p>The container process will end and your original shell will be released.</p>
