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.
--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.
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.