Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all Docker containers except one

Tags:

docker

I have script that stops containers and then removes them

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

But I don't want to remove the docker container with name "my_docker".

How can I remove all containers except this one?

like image 712
nick_gabpe Avatar asked Nov 22 '16 14:11

nick_gabpe


Video Answer


2 Answers

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

like image 60
nwinkler Avatar answered Oct 09 '22 20:10

nwinkler


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.

like image 32
Cybernetic Avatar answered Oct 09 '22 20:10

Cybernetic