This question is related to Should I be concerned about excess, non-running, Docker containers?.
I'm wondering how to remove old containers. The docker rm 3e552code34a
lets you remove a single one, but I have lots already. docker rm --help
doesn't give a selection option (like all, or by image name).
Maybe there is a directory in which these containers are stored where I can delete them easily manually?
You can use the following command to remove the exited containers:
Here is the full gist to also remove the old images on docker: Gist to remove old Docker containers and images.
The basic steps to stop/remove all containers and images
List all the containers
docker ps -aq
Stop all running containers
docker stop $(docker ps -aq)
Remove all containers
docker rm $(docker ps -aq)
Remove all images
docker rmi $(docker images -q)
Note: First you have to stop all the running containers before you remove them. Also before removing an image, you have to stop and remove its dependent container(s).
Updated Answer Use
docker system prune
ordocker container prune
now. See VonC's updated answer.Previous Answer Composing several different hints above, the most elegant way to remove all non-running containers seems to be:
docker rm $(docker ps -q -f status=exited)
-q
prints just the container ids (without column headers)-f
allows you to filter your list of printed containers (in this case we are filtering to only show exited containers)Remove all stopped containers.
This will remove all stopped containers by getting a list of all containers with docker ps -a -q and passing their ids to docker rm. This should not remove any running containers, and it will tell you it can’t remove a running image.
Remove all untagged images
Now you want to clean up old images to save some space.
It is now possible to use filtering with
docker ps
:And for images:
However, any of those will cause
docker rm
ordocker rmi
to throw an error when there are no matching containers. The olderdocker rm $(docker ps -aq)
trick was even worse as it tried to remove any running container, failing at each one.Here's a cleaner script to add in your
~/.bashrc
or~/.profile
:Edit: As noted below, original answer was for removing images, not containers. Updated to answer both, including new links to documentation. Thanks to Adrian (and Ryan's answer) for mentioning the new
ps
filtering.Try this command to clean containers and dangling images.