Docker Remove, delete and cleanup containers


Example

docker rm can be used to remove a specific containers like this:

docker rm <container name or id>

To remove all containers you can use this expression:

docker rm $(docker ps -qa)

By default docker will not delete a container that is running. Any container that is running will produce a warning message and not be deleted. All other containers will be deleted.

Alternatively you can use xargs:

docker ps -aq -f status=exited | xargs -r docker rm 

Where docker ps -aq -f status=exited will return a list of container IDs of containers that have a status of "Exited".

Warning: All the above examples will only remove 'stopped' containers.

To remove a container, regardless of whether or not it is stopped, you can use the force flag -f:

docker rm -f <container name or id>

To remove all containers, regardless of state:

docker rm -f $(docker ps -qa)

If you want to remove only containers with a dead status:

docker rm $(docker ps --all -q -f status=dead)

If you want to remove only containers with an exited status:

docker rm $(docker ps --all -q -f status=exited)

These are all permutations of filters used when listing containers.

To remove both unwanted containers and dangling images that use space after version 1.3, use the following (similar to the Unix tool df):

$ docker system df

To remove all unused data:

$ docker system prune