How to automatically delete a Docker container after running it

Print Friendly, PDF & Email

Normally, a Docker container persists after it has exited. This allows you to run the container again, inspect its filesystem, and so on. However, sometimes you want to run a container and delete it immediately after it exits. Docker provides the –rm command-line option for this purpose:

docker run --rm <name_of_docker_image>

This command will create a running container from the « name_of_docker_image » image and delete the container immediately after we stop it. This helps to prevent having to clean up containers after you’re done your experiment.

Note:  The --rm flag is required to archive this purpose doesn’t work in conjunction with the -d (–detach) flag. When the --rm flag is set, Docker also removes the volumes associated with the container when the container is removed. This is similar to running docker rm -v my-container. Only volumes that are specified without a name are removed.

For example:

docker run -it --rm -v /etc -v logs:/var/log centos /usr/local/bin/tomcat/logs

With the command above, the volume of /etc will be removed, but the volume of /var/log will not. Volumes inherited via --volumes-from will be removed with the same logic — if the original volume was specified with a name it will not be removed.

That’s it!

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *

*

code

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.