How to docker remove a container when it exits


When you run a docker image and a container is created, when the container exists docker will not remove the container that existed by default, let's see this by creating multiple containers from fedora image,

Container 1:
% docker run fedora echo hello1
hello1
Container 2:
% docker run fedora echo hello2
hello2
Container 3:
% docker run fedora echo hello3
hello3

Now, if I do a docker ps -a to see the list of all containers, I see that there are 3 containers that exited but have not been removed and utilizing memory.

% docker ps -a
CONTAINER ID   IMAGE     COMMAND         CREATED          STATUS                      PORTS     NAMES
e9072f3eff69   fedora    "echo hello3"   9 seconds ago    Exited (0) 9 seconds ago              thirsty_almeida
21abcc335be3   fedora    "echo hello2"   11 seconds ago   Exited (0) 11 seconds ago             interesting_turing
0c0ba20b0018   fedora    "echo hello1"   57 seconds ago   Exited (0) 56 seconds ago             cool_robinson

If you wish to remove the created container when the docker run command completes, you should add --rm option to the docker run command.

Example: Docker run with --rm option:
% docker run --rm fedora echo hello4
hello4
Docker remove container when run completes example
-


Have Questions? Post them here!

Top Hashtags:

Advertisements

Advertisements




Advertisements