Docker disconnect all containers from docker network

9k views Asked by At

I have docker network "my_network". I want to remove this docker network with docker network rm my_network. Before it I should disconnect all my containers from this network. I can use docker network inspect and get output like

[
    {
        "Name": "my_network",
        "Id": "aaaaaa",
        "Scope": "some_value",
        "Driver": "another_value",
        "EnableIPv6": bool_value,
        "IPAM": {
            "Driver": "default",
            "Options": {},
            "Config": [
                {
                    "Subnet": "10.0.0.0/1"
                }
            ]
        },
        "Internal": false,
        "Containers": {
            "bbb": {
                "Name": "my_container_1",
                "EndpointID": "ENDPOITID1",
                "MacAddress": "MacAddress1",
                "IPv4Address": "0.0.0.0/1",
                "IPv6Address": ""
            },
            "ccc": {
                "Name": "my_container_2",
                "EndpointID": "ENDPOINTID2",
                "MacAddress": "MacAddress2",
                "IPv4Address": "0.0.0.0/2",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]

It is okay to manual disconnect if I have only several containers but if I have 50 containers I have problem. How can I disconnect all containers from this network with single or several command?

1

There are 1 answers

3
VonC On BEST ANSWER

docker network inspect has a format option.

That means you can list all Container names with:

docker network inspect -f '{{range .Containers}}{{.Name}}{{end}}' network_name

That should then be easy, by script, to read each name and call docker network disconnect.

wwerner proposes below in the comments the following command:

for i in ` docker network inspect -f '{{range .Containers}}{{.Name}} {{end}}' network_name`; do docker network disconnect -f network_name $i; done;

In multiple line for readability:

for i in ` docker network inspect -f '{{range .Containers}}{{.Name}} {{end}}' network_name`;\
  do \
     docker network disconnect -f network_name $i; \
  done;

Adding:

Note that there is a space in the format as opposed to the answer to split the names by a space.