Articles


How to automatically delete a Docker container after running it

How to automatically delete a Docker container after running it



Posted bynitheesh,31st Aug 2016

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 my-docker

This will create a container from the "my-docker" image and delete the container immediately after it exits. This helps to prevent having to clean up containers after you're done experimenting.

Note: The --rm flag doesn't work in conjunction with the -d (--detach) flag.
When --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.