Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically stop and remove Docker container on Ctrl+C in terminal/gitbash/powershell/etc.?

Tags:

docker

For example I run

docker run --rm --name mycontainer -p 8080:8080 myrepo/myimage

then I see an output of my application, everything is OK. Then I press the Ctrl+C but the container is still running and I'm forced to explicitly stop and remove it:

docker rm -f <container_id>

Or even worse:

docker stop <container_id>
docker rm <container_id>

Is there any way to do it automatically? If not it's OK.

PS: What is the purpose of all that stopped containers still kept on the harddrive?!

like image 997
ieXcept Avatar asked Dec 28 '17 13:12

ieXcept


Video Answer


1 Answers

What is the purpose of all that stopped containers still kept on the harddrive?!

Running containers include the process you are running along with the namespaced environment to run that process inside of (networking, pid, filesystem, etc).

A stopped container has the container specific read/write filesystem layer, any configuration you included to run the container (e.g. environment variables), and logs if you are using the json logging driver (default).

Removing a container deletes that RW filesystem layer, json logs, and the configuration, which also removes the container from the list of stopped containers. This is a permanent operation, so do not remove containers you may want to later inspect or restart.

I press the Ctrl+C but the container is still running and I'm forced to explicitly stop and remove it

First, make sure you are running a current version of docker. I believe somewhere around 1.13 they migrated the processing of the --rm option from the client to the server. Next, make sure your application handles the Ctrl+C command. In a shell script, this would be a handler for a SIGTERM. You also need run the container interactively so that the keyboard input is sent to the container, that is the -it flag. With all three of those done, you should see containers automatically cleaned up with:

docker run --rm -it --name mycontainer -p 8080:8080 myrepo/myimage

followed by a Ctrl+C. The -it will pass the SIGTERM to the container which should then stop the process, which stops the running container. And the --rm will result in the container being automatically removed.

If for some reason you cannot get your container to handle the SIGTERM, then you can send a SIGKILL with a docker kill command, which cannot be trapped and ignored by the application.

Note that if you run a docker stop on your container and see a 10 second delay before it is stopped, then your application is ignoring the SIGTERM. One common cause for this is a /bin/sh running as pid 1. A shell will ignore this signal when it's running as pid 1 by default, on the assumption that you are in signal user mode.

like image 120
BMitch Avatar answered Sep 29 '22 09:09

BMitch