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?

  • Export tar of changed files in container
  • How do I save kubectl logs to a file on my host machine?
  • Docker and single python file
  • Build Docker in VM
  • Setting up a pycharm license server
  • Dockerfile CMD `command not found`
  • Docker stack deploy rolling updates volume issue
  • How to upgrade npm to npm@5 on the latest node docker image?
  • Two Logstash instances on same Docker container
  • Docker RUN statement (modifying a file) not executed
  • Docker swarm mode scale service issue with one worker
  • ASP.NET docker image exposed ports are closed
  • 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.