Delete all but one Docker container

I have a script that stops containers and then deletes them

docker stop $(docker ps -q) docker rm $(docker ps -a -q) 

But I do not want to delete the dock container named "my_docker".

How can I delete all containers except this?

+19
source share
7 answers

You can try this what will

  • Filter out the unwanted element ( grep -v ) and then
  • returns the first column that contains the container identifier

Run this command:

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

To use cut instead of awk , try the following:

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

Examples of using awk / cut here: bash: the shortest way to get the nth output column

+26
source

The title of the question defines images , not containers. For those who stumbled upon this question while looking at deleting all but one of the images , you can use docker prune along with filter flags:

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

replacing filename with the name of your image.

You can also use the do = flag to crop images by date.

+11
source

This is what docker rm $(List of container Ids) actually happens. So this is just a question of how you can filter the list of container identifiers.

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

+6
source

I would rather check the container name using something along the lines (untested)

docker inspect --format '{{ .Name }}' $(docker ps -aq)

this will give the names of the containers (working or not) and you can filter and

docker rm

using this information

+1
source

Old question, but I like to animate messages.

In this case, you can use Spotify Docker GC: https://github.com/spotify/docker-gc#excluding-containers-from-garbage-collection

You can do:

 echo "my_docker" >> /tmp/docker-gc-exclude-containers echo '*' > /tmp/docker-gc-exclude docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v /etc:/etc:ro -v /tmp/docker-gc-exclude-containers:/etc/docker-gc-exclude-containers:ro -v /tmp/docker-gc-exclude:/etc/docker-gc-exclude:ro spotify/docker-gc 

(if you want your images to be cleaned too, you can avoid installing the docker-gc-exclude file)

0
source

To stop

 docker stop $(docker ps -a -q | grep -v "my_container_id") 

Delete

 docker rm $(docker ps -a -q | grep -v "my_container_id") 
0
source

I achieved this with the following command:

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

Source: https://habr.com/ru/post/1260143/


All Articles