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?

  • Pull image with docker-compose run
  • Just created Docker Hub account, credentials do not work for “docker login”
  • set environment variable in running docker contianer
  • Getting docker logs to graylog2 AND locally
  • Prevent skip in docker-compose
  • Share data between 2 containers
  • Can a docker image use executable from the host?
  • Docker on RHEL 6 Cgroup mounting failing
  • Docker Quickstart Terminal: exit status 255
  • Docker install PHP-7-fpm with Memcache extention ? fails with Cannot find config.m4
  • docker swarm - if the container in a service dies on an error, will the task be replicated elsewhere?
  • Where do yesod binaries expect to find the config folder?
  • 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:

    #!/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
    
    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.