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?

  • how to bind ports with docker-py
  • Problems running kapacitor localinstall inside dockerfile
  • How to expose docker container's ip and port to outside docker host without port mapping on TinyCore?
  • Docker: Nginx & PHP Container: no such file or directory
  • docker build taking too much time in aws ecs
  • Docker - Why is this express.js container with an exposed/published port reject connections? (using boot2docker)
  • Run tests inside Docker container with Jenkins
  • Docker container stdout, stderr is being truncated. Is there a way to stop this?
  • Docker Swarm DNS server address
  • Run multiple docker-compose (one per machine)
  • How to add Zend Guard Loader support in docker php official image instance?
  • Why does my automated build run so slowly inside a Docker container?
  • One Solution collect form web for “How to execute a script when I terminate a docker container”

    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:

    #Define cleanup procedure
    cleanup() {
        echo "Container stopped, performing cleanup..."
    #Trap SIGTERM
    trap 'cleanup' SIGTERM
    #Execute a command
    "${@}" &
    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 $!
    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.