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!
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.