Search code examples
dockerdockerfiledocker-entrypoint

How can I execute a command/script after issuing "docker container stop" command?


I would like a container to run a determined command before it stops after issuing the command "docker container stop". I have found the question How to execute a script when I terminate a docker container but it does not really work as the container keeps crashing after creating it, even if I add an infinite loop to execute when run. I'm running the container as: docker run -ti -d --name test stop_test

What could be wrong?

This is my docker file:

#Starting with a ubuntu image
FROM ubuntu

#Installing all dependencies

#Copying files
COPY loop.sh .
COPY commands.sh .
COPY stop.sh .

#Running new container
RUN chmod +x commands.sh
RUN chmod +x stop.sh
CMD ["./commands.sh"]

#Adding Entrypoint
ENTRYPOINT [ "/bin/bash", "-c", "./stop.sh" ]

The stop script is:

#!/bin/bash

#Defining cleanup procedure
cleanup() {
    echo "Container stopped. Running script..."
}

#Trapping the SIGTERM
trap 'cleanup' SIGTERM

#Execute a command
less /etc/password &

#Wait
wait $!

#Cleanup
cleanup

The loop script:

#!/bin/bash

while :
do
 sleep 300
done

The commands script is:

#!/bin/bash

./loop.sh

Solution

  • The problem was in the command being executed by the stop.sh script. I replaced it by the infinite loop script and worked well.