How to Exit and Kill the Running Docker Container with CTRL+C?

3/1/2019

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


Background

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

# content of sync.sh

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

So based on the shell script, I then created a Docker Image with the following Dockerfile content:

FROM debian:stretch 
COPY sync.sh .

ENTRYPOINT ["/sync.sh"]

and build the image by running docker build -t infinite-loop .

Problem

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

  1. docker run --rm to-infinity-1 infinite-loop
  2. docker run --rm -it to-infinity-2 infinite-loop
  3. docker run --rm -d to-infinity-3 infinite-loop, then run docker attach on to-infinity-3

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

Thank you.

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

-- dekauliya
bash
docker
google-kubernetes-engine
kubernetes
shell

2 Answers

3/1/2019

I think you'll need to use trap, here's an example of my code:

done=0
trap 'done=1' TERM INT

while [ $done = 0 ]; do
  #doingstuff
  sleep $someinterval &
  wait
done

ctrl + c is a signal so you'll need a signal handler. Moreover sleep will need to be run in background so that your trap won't be held until sleep is completed.

[1] Trap: https://www.shellscript.sh/trap.html

-- irvifa
Source: StackOverflow

3/1/2019

“docker run” traps or ignores ctrl+c.

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

Open a new shell and execute

$ docker ps # get the id of the running container
$ docker stop <container> # kill it (gracefully)

The container process will end and your original shell will be released.

-- Aman Gupta
Source: StackOverflow