Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trapping signal from "docker stop" in bash

Tags:

i have an entry point script in a docker container that looks something like the following:

#!/bin/bash  echo starting up  function shut_down() {     echo shutting down      pid=$(ps -e | grep myapp | awk '{print $1}')     kill -SIGTERM $pid       exit }  trap "shut_down" SIGKILL SIGTERM SIGHUP SIGINT EXIT  /opt/myapp 

I can't figure out how to trap the signal sent in by running docker stop on the container. When running interactively, a ctrl+c will trigger it as expected, but a docker stop command just waits for the 10 second timeout, and exits without ever entering the shut_down function

How can I trap the signal sent by docker stop in bash to do some cleanup?

like image 726
ben schwartz Avatar asked Dec 16 '13 02:12

ben schwartz


2 Answers

Old question, but this will do the trick:

#!/bin/bash  echo starting up  exec /opt/myapp 

For details take a look here: https://akomljen.com/stopping-docker-containers-gracefully/

like image 128
Alen Komljen Avatar answered Sep 20 '22 13:09

Alen Komljen


Have a look at this, could be inspiring :-)

UPDATE:

@nick-humrich here it is is my lamer copy & past (credit goes to the original author https://github.com/lgierth )

#!/bin/bash  function ensure_started_container {   exists=`docker ps -q | grep $1`   if [ "$?" = "0" ] ; then     echo "[docker-exec] skipping docker start, already started"   else     output=`docker start "$1"`     echo "[docker start] $output"   fi   running=1 }  function setup_signals {   cid="$1"; shift   handler="$1"; shift   for sig; do     trap "$handler '$cid' '$sig'" "$sig"   done }  function handle_signal {   echo "[docker-exec] received $2"   case "$2" in     SIGINT)       output=`docker stop -t 5 "$1"`       echo "[docker stop] $output"       running=0       ;;     SIGTERM)       output=`docker stop -t 5 "$1"`       echo "[docker stop] $output"       running=0       ;;     SIGHUP)       output=`docker restart -t 5 "$1"`       echo "[docker restart] $output"        # restart logging       docker attach "$1" &       kill "$logger_pid" 2> /dev/null       logger_pid="$!"       ;;   esac }  running=0  setup_signals "$1" "handle_signal" SIGINT SIGTERM SIGHUP  ensure_started_container "$1"  docker attach "$1" & logger_pid="$!"  while true; do   if [ "$running" = "1" ]; then     sleep 1   else     break   fi done  exit_code=`docker wait "$1"` exit "$exit_code" 
like image 30
Luca G. Soave Avatar answered Sep 21 '22 13:09

Luca G. Soave