Docker is a convenient tool to quick create containers from different Linux images. If we use the common way to start a docker container like
docker run image bash, after the the process exists, the container is still stored there. That is, the docker container persists after it has exited. Sometimes, we would like to do quick tests and tries in some Linux environments in the docker images. And after the program exits, we would like to have the exited container automatically removed.
Start a docker container that will be automatically removed after being stopped
Docker has the support for this kinds of usage. The key option is to use the
--rm option for the
docker run command.
--rm true|false Automatically remove the container when it exits. The default is false. --rm flag can work together with -d, and auto-removal will be done on daemon side. Note that it's incompatible with any restart policy other than none.
To start a docker container (from
bash) that will be automatically removed (deleted):
$ docker run -it --rm ubuntu:18.04 bash
Verify the container will be automatically removed
After we run that, a new container will be created and the
bash shell is ready:
Now the container can be listed by
$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e18acbc47561 ubuntu:18.04 "bash" 7 minutes ago Up 7 minutes priceless_matsumoto
Now let’s exit the cotainer by running
exit in the container:
root@e18acbc47561:/# exit exit
Then, let’s verify the container is really removed using
docker ps -a so that all stopped containers will be shown too:
$ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
The container is gone as expected.