1

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
4
  • is not it the solution? stackoverflow.com/questions/35808251/… Commented Mar 24, 2021 at 18:37
  • From what I understand one of the answers links to some examples where they recommend using a script. That's what I'm doing, but container crashes. Commented Mar 24, 2021 at 18:47
  • What do you mean by crashes? What output and logs do you receive? Commented Mar 24, 2021 at 19:39
  • It's been solved! Thanks! Commented Mar 24, 2021 at 20:45

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

please share your solution code

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.