2

I'm trying to execute a piece of code when the user presses Ctrl+C in a Bash script, which makes an HTTP request to the running Docker container and saves the result to a local directory, before the container shuts down.

I've read on other posts that to prevent Ctrl+C being sent to child processes, I can use trap, like so:

function sigint_handler () {
  echo "Saving container state..."
  curl "http://localhost:$CONTAINER_PORT/api/state" > container_state.json
  exit
}

trap sigint_handler INT

docker-compose up

However, this doesn't seem to be working. It looks like docker-compose is receiving the Ctrl+C and getting shut down first, then my SIGINT handler is executing:

^CGracefully stopping... (press Ctrl+C again to force)
Stopping metrics_grafana_1    ... done
Stopping metrics_prometheus_1 ... done
Saving container state...

How can I get my SIGINT handler to execute, then send SIGINT to docker-compose?

Brandon
  • 1,336
  • 3
  • 10
  • 38
  • this question has nothing to do with docker really, right? You're running a program in the foreground and thus it receives the Ctrl-C from the terminal, and you want to receive that input yourself. It isn't really relevant that it's docker – erik258 Nov 22 '20 at 01:48
  • If you're genuinely asking me whether it has anything to do with Docker, the answer is "I don't know." I have a hunch that the behavior might be specific to the way `docker-compose` handles signals, but I might be wrong, hence why I'm asking this question. In other StackOverflow posts, I've seen that this pattern is used to prevent Ctrl+C from being sent to child processes. But I figure there must be something special about `docker-compose` that prevents this from working. – Brandon Nov 22 '20 at 01:50
  • pretty sure it doesn't. to find out, why not create a test environment and take docker-compose out of the equation? Since `docker-compose up` is the foreground process, the fact that `docker-compose up` gets the Ctrl-C signal is not at all unusual. The same thing would happen if you ran an interactive bash shell, ran `cat` , and then pressed Ctrl-C. What surprises me here is that in this assumedly *non*interactive shell, the Ctrl-C signal hits bash itself. I experiment a lot with this kind of thing to better understand it, and you can too, on, eg, https://repl.it/ (no affiliation). – erik258 Nov 22 '20 at 01:59
  • 1
    Have you considered trapping the TERM signal *in your app* to handle whatever you're asking the container to do from outside docker compose? That would be a more elegant solution, because https://stackoverflow.com/questions/2524937/how-to-send-a-signal-sigint-from-script-to-script – erik258 Nov 22 '20 at 02:18

0 Answers0