DEV Community

Tim Salva
Tim Salva

Posted on • Edited on • Originally published at blog.jtsalva.dev

How to remove all docker containers in a network

Update
Thanks @hasnayeen for making me aware of the following better approach

docker <stop|rm> $(docker ps -qf "network=<NAME>")
Enter fullscreen mode Exit fullscreen mode

Steps

How to list docker containers in a network

Inspecting a docker network will list containers along with other information, we can use the --format flag to get a newline separated list.

docker network inspect <NAME> --format='{{range $id, $_ := .Containers}}{{println $id}}{{end}}

// Example output
197123ceff4c60ad99518e948047d842eab52ab7eac38476dabe22ac5f6cc209
2ec40124c66a394d6f29e1448bff3182902a94e74f923c7cab4f10c3d7f99d1d
aeb2b9d5686efcf186adf13ce6b8471782f332385aa8b2c4314932a1416f8376
Enter fullscreen mode Exit fullscreen mode

Stopping and removing containers in a docker network

docker <stop|rm> $(docker network inspect <NAME> \
    --format='{{range $id, $_ := .Containers}}{{println $id}}{{end}}')
Enter fullscreen mode Exit fullscreen mode

After much Googling I couldn't find how to do this anywhere, if there's a better way please let me know.

Top comments (2)

Collapse
 
hasnayeen profile image
Nehal Hasnayeen

you can use this command to remove all containers in a network

docker rm $(docker ps -q -f "network=<NAME>")
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jtsalva profile image
Tim Salva

Thanks @hasnayeen , time for me to switch to using this.