As I am creating the docker tutorials “for biologists” I find that having some notes here could be useful. This is therefore a bit like a Frequently Asked Questions (FAQ) that I answer to myself at first!
For general info it would be best to refer to the tutorials themselves when they are online.
Remove many stopped containers
When a container is created by launching a docker image with docker run
the container will be created and stay on the hard drive even after it has exited unless the modifier --rm
is added on the command. Otherwise, there will be an accumulation of “dead” or “dormant” containers.
To view them we can use the command docker container ls --all
to see the complete list.
The command docker container ls -aq
is very useful (see below) to remove a large number of containers.
To remove all of the containers we can use this bash
command where the backtick (`
) is used to “isolate” and run the listing of containers first, which is then passed onto the remove (rm
) command from docker
docker rm `docker container ls -aq`
What is inside the backticks is evaluated first, and the unix pipe (|
) can be used, for example to remove the first 3 that appear on the list:
docker rm `docker container ls -aq | head -3`
A more sophisticated method, inspired by this post consists in creating a variable cont
containing the list of all the containers (here limited to the top 29.) Note the use of the curly brackets ({ }
. )
for cont in {`docker container ls -aq | head -29`} > do > docker container rm ${cont} > done
Some containers may need to be stopped before it is possible to remove them. For example:
docker container stop f0b389579b8d f0b389579b8d docker container rm f0b389579b8d
EDIT: On the docker-curriculum.com tutorial they offer simpler commands that also specifies to remove only the docker containers that have stopped (exited) therefore avoiding conflicts:
docker rm $(docker ps -a -q -f status=exited)
This command deletes all containers that have a status of exited
. In case you’re wondering, the -q
flag, only returns the numeric IDs and -f
filters output based on conditions provided. […]
In later versions of Docker, the docker container prune
command can be used to achieve the same effect.
docker container prune
A warning is then given:
WARNING! This will remove all stopped containers.
Are you sure you want to continue? [y/N] y
The containers are then deleted and reclaimed disk space printed.