How to stop and remove docker containers in a network

·

1 min read

Update

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

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

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

Stopping and removing containers in a docker network

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

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