B_B
B_B

Reputation: 2013

Run a script when docker is stopped

I am trying to create docker container using dockerfile where script-entry.sh is to be executed when the containers starts and script-exit.sh to be executed when the container stops.

ENTRYPOINT helped to accomplish the first part of the problem where script-entry.sh runs on startup.

How will i make sure the script-exit.sh is executed on docker exit/stop ?

Upvotes: 21

Views: 20750

Answers (2)

CtheGood
CtheGood

Reputation: 1019

Create a script, and save it as a bash file, that contains that following:

$CONTAINER_NAME="someNameHere"
docker exec -it $CONTAINER_NAME bash -c "sh script-exit.sh"
docker stop $CONTAINER_NAME

Run that file instead of running docker stop, and that should do the trick. You can setup an alias for that as well.

As for automating it inside of Docker itself, I've never seen it done before. Good luck figuring it out, if that's the road you want to take.

Upvotes: -6

Xiongbing Jin
Xiongbing Jin

Reputation: 12107

docker stop sends a SIGTERM signal to the main process running inside the Docker container (the entry script). So you need a way to catch the signal and then trigger the exit script.

See This link for explanation on signal trapping and an example (near the end of the page)

Upvotes: 21

Related Questions