How to run a closing script when issuing docker-compose stop or crtl-c

415 Views Asked by At

I'm doing:

docker-compose up

my service is essentially to run netlify dev

Because we may deal with several _redirects_xxx files, I have in my entrypoint.sh something like:

cleanup() {
    if $remove; then
        echo ">>> Removing created _redirects"
        rm -fv /app/_redirects
    else
        echo "Bye!"
    fi
}
reddoc=${1}
remove=false
if [ ! -s "/app/_redirects" ]; then
    echo ">>> Copying ${reddoc} to _redirects"
    cp /app/${reddoc} /app/_redirects
    remove=true
else
    echo ">>> _redirects already exists"
fi
trap 'cleanup' INT TERM EXIT
echo ">>> remove = ${remove}"
netlify dev

From my docker-compose.yml, I have:

...
   frontend:
      volumes:
      - ./frontend/:/app
      - node_modules:/app/node_modules
...
      init: true
      command: bash ./entrypoint.sh _redirects_docker
...

The point is, some developers have their own _redirects file so when starting the docker service, we don't want to override their setup. But for all other developers (mostly backend guys) we want the _redirects_docker to take place but, when stopping the frontend service (e.g. crtl-C or docker-compose stop / down), I'd like a closure step to remove the _redirects file if it was not there from the very beginning.

I've tried, as you may see, above with TRAP and init but it's not working to delete _redirects.

UPDATE 25/Nov/2020

Not a solution yet, but I found out that if I do this in another terminal:

docker kill -s hup frontend_1

It triggers the trap and does what I want. However using -s int or -s term does not do anything.

UPDATE 26/Nov/2020

I found out that the issue is on how to trap netlify dev. If I use a zombie line instead, like, while true; do :; done, stopping the docker service, no matter how, except with a pure kill, will trigger the routine cleanup.

Honestly, an exitpoint: pragma in docker-compose.yml would be all I ever wanted.

1

There are 1 best solutions below

0
On

In the end, this worked for me by amending entrypoint.sh with:

...
netlify dev | tee dev.log &
wait