Remove all Docker containers except one

The title of the question asks for images, not containers. For those stumbling across this question looking to remove all images except one, you can use docker prune along with filter flags:

docker image prune -a --force --filter "label!=image_name"

replacing image_name with the name of your image.

You can also use the "until=" flag to prune your images by date.


This is what's actually happening docker rm $(List of container Ids). So it's just a matter of how you can filter the List of Container Ids.

For example: If you are looking to delete all the container but one with a specific container Id, then this docker rm $(docker ps -a -q | grep -v "my_container_id") will do the trick.


I achieved this by the following command:

docker image rm -f $(docker images -a | grep -v "image_repository_name" | awk 'NR>1 {print $1}')

You can try this, which will

  • Filter out the unwanted item (grep -v), and then
  • returns the first column, which contains the container id

Run this command:

docker rm $(docker ps -a | grep -v "my_docker" | awk 'NR>1 {print $1}')

To use cut instead of awk, try this:

docker rm $(docker ps -a | grep -v "my_docker" | cut -d ' ' -f1)

Examples for awk/cut usage here: bash: shortest way to get n-th column of output

Tags:

Docker