Search code examples
docker

Remove all Docker containers except one


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?


Solution

  • 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