Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

How to execute a script when I terminate a docker container

I want when I type on my console:

docker ^a docker container^ stop

To execute a script before terminating. is that possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The docker stop command attempts to stop a running container first by sending a SIGTERM signal to the root process (PID 1) in the container. If the process hasn't exited within the timeout period a SIGKILL signal will be sent.

In practice, that means that you have to define an ENTRYPOINT script, which will intercept (trap) the SIGTERM signal and execute any shutdown logic as appropriate.

A sample entrypoint script can look something like this:

#!/bin/bash

#Define cleanup procedure
cleanup() {
    echo "Container stopped, performing cleanup..."
}

#Trap SIGTERM
trap 'cleanup' SIGTERM

#Execute a command
"${@}" &

#Wait
wait $!

(shell signal handling, with respect to wait, is explained in a bit more details here)

Note, that with the entrypoint above, the cleanup logic will only be executed if container is stopped explicitly, if you wish it to also run when the underlying process/command stops by itself (or fails), you can restructure it as follows.

...

#Trap SIGTERM
trap 'true' SIGTERM

#Execute command
"${@}" &

#Wait
wait $!

#Cleanup
cleanup

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...