'How to terminate a Docker container which is running as part of bash script when the bash script is killed?
#/bin/bash
docker run ubuntu sleep 3000
I have a bash script which runs docker container but when the script is terminated using kill -9 pid [SIGKILL]
the docker container continues to run.
How can i terminate the docker container when bash script is killed?
I tried using trap but SIGKILL signal can't be trapped so i am trying to find if there are any alternate ways to stop the container
Solution 1:[1]
Actually you can stop your docker container.
docker run ubuntu sleep 3000
will create a docker image an launch it in a container.
docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
59ba158952c9 ubuntu "sleep 3000" 4 seconds ago Up 3 seconds infallible_jackson
34fbe4742f34 ubuntu "sleep 1000" 40 seconds ago Exited (137) 17 seconds ago confident_perlman
80a4d44a23be ubuntu "sleep 1000" 2 minutes ago Exited (137) About a minute ago busy_colden
e40b91d7b13f ubuntu "sleep 100" 4 minutes ago Exited (0) 2 minutes ago trusting_merkle
then you can docker stop 59ba158952c9 (id of the container you want to stop). and the remove it if necessary
docker rm 59ba158952c9
I suggest you to have a look at the following documentations: https://docs.docker.com/engine/reference/commandline/stop/ https://docs.docker.com/engine/reference/commandline/container_rm/
Sorry my answer was not full complete.
let's add the docker command in a script
echo "docker run ubuntu sleep 3000" > toto.sh
then kill -9 the script: ps -aux | grep toto
mytoto+ 1320784 0.0 0.0 12664 3288 pts/15 S+ 07:49 0:00 bash toto.sh
then the docker container is still active and you and retrieve it with a grep for instance:
docker ps | grep "ubuntu.*sleep 3000" | cut -d" " -f1
2baf9fb7223d
copy the id in the variable ID
ID=$(docker ps | grep "ubuntu.*sleep 3000" | cut -d" " -f1)
echo $ID
2baf9fb7223d
And finally stop / remove the container
docker container stop "${ID}"
docker container rm "${ID}"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
