Remove Docker container after it Exits
Docker container persists after it has finished execution (exited) so that it can be run again or file system can be inspected. There can be times when all you want to do is run a container for a specific task and delete after t exits.
Docker has an option — rm for this purpose.
docker run — rm my-image
This command will pull image my-image, run a container and delete it after it exits.
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.