22

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 ?

4
  • Docker daemon logs everything, why not write a script/program that parse the logs and, when the even containerID stops appears execute the script you want to. Commented Mar 5, 2016 at 9:17
  • 1
    @Auzias There is an event api and an events command built into docker that would be better suited to tasks like that Commented Mar 6, 2016 at 9:44
  • @Auzias also running a something after the stop event will likely not be able to run or get interrupted. Commented Mar 6, 2016 at 9:52
  • To run a script on the host when a container exits, see superuser.com/questions/1464366/… Commented Dec 1, 2023 at 13:10

2 Answers 2

22

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)

Sign up to request clarification or add additional context in comments.

Comments

-6

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.

1 Comment

It does not answer the question. The question is: "how to execute a script once a container is stopped", which is different from "how to execute a script and then stop the container"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.