Docker : how to launch a script on host when container stops?

3

I would like to know if it is possible to launch bash script on host when a docker container is stopped.

For example I would like to stop a service when my container is stopped.

I saw that catching the SIGTERM signal is possible and that you can then execute some bash commands in the container. Maybe there is a way to catch the SIGTERM signal on the host machine and then launch a script...

M.Brbr

Posted 2019-07-26T12:50:12.563

Reputation: 129

Answers

3

Try docker events using appropriate filter. I.e.

$ docker events --filter 'container=alpine-bash' --filter 'event=stop'
> 2019-07-26T17:25:35.944807432+04:00 container stop 5db8ba01c4ca26b4417bd080d9022b74893a865eefe22dc987f8d18fda104f39 (image=yikaus/alpine-bash, name=alpine-bash)

Yasen

Posted 2019-07-26T12:50:12.563

Reputation: 166

0

You can use the docker container wait command:

$ docker container wait --help

Usage:  docker container wait CONTAINER [CONTAINER...]

Block until one or more containers stop, then print their exit codes

An example usage looks like:

$ docker run -d --rm --name test-wait busybox sleep 10
9ca77ac5121690110e8fdf58e73583918fa9b1a5de56ab89eb70cc89be97f3fa

$ docker container wait test-wait
0

The second command hung until the container's sleep command finished.

BMitch

Posted 2019-07-26T12:50:12.563

Reputation: 484