Wednesday, 20 May 2020

Docker Management: Clean up all services, containers and images on a Docker host

The following commands can be used to clean up a Docker host. This could be useful if you have been learning about Docker and want to get your lab hosts back to a vanilla state. They could of course work in production but please use the commands with caution.

Remove all services

docker service rm $(docker service ls -q)

This command queries Docker for a list of services and pipes the output to the docker service rm command. You could of course use it with a single service reference, for example:

docker service rm service name/id

Remove all containers

docker ps -aq

Use the ps -aq command to find a list of all the containers running on a Docker host. 

docker stop $(docker ps -aq)

The first step is to use docker stop and pipe the output of docker ps -aq to force all running containers on the system to stop. 

docker rm $(docker ps -aq)

The last step to actually rm the containers from the host, again pipe ps -aq into the docker rm command to achieve this. 

Remove all images

docker rmi $(docker images -q)

This command removes all the images from the Docker host.

docker image prune

This command will remove all images which are not associated with a running or stopped container. Obviously if you have rm'd all the images this command is not needed. But its a good maintenance exercise to complete on a production host when optimsing disk space.