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. For example to execute a command or show a file from the filesystem. Docker provides the
--rm command line option for this purpose:
docker run --rm ubuntu cat /etc/hosts
This will create a container from the "ubuntu" image, show the content of /etc/hosts file and then delete the container immediately after it exits. This helps to prevent having to clean up containers after you're done experimenting.
--rmflag doesn't work in conjunction with the
--detach) flag in docker < 1.13.0.
--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, with
docker run -it --rm -v /etc -v logs:/var/log centos /bin/produce_some_logs, 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.