How to list Networks; a docker container is attached to using format template?

Viewed 1110

When I want to check a list of containers a bridge driver is connected to, I do the followings,

docker network inspect br01 --format='{{range .Containers}}{{println .Name}}{{end}}'

Which gives the following output,

network-test01
network-test02
network-test03

But how to do the same for listing network drivers a container is connected to?

Following is docker inspect,

.....
            "Networks": {
                "br01": {
                    "IPAMConfig": {},
                    "Links": null,
                    ........
                },
                "bridge": {
                    "IPAMConfig": null,
                    .....
                }
.....

I just want to list the Networks like the following,

br01
bridge

I have tried the following but can't properly work through the template due to my limited knowledge in go templates.

docker inspect network-test01 --format "{{.NetworkSettings.Networks}}"

Which results the following,

map[br01:0xc0000f6180 bridge:0xc0000f6cc0]
1 Answers

The following template will output just the network names:

{{range $k, $v := .NetworkSettings.Networks}}{{println $k}}{{end}}

Example Go code testing it:

m := map[string]interface{}{
    "NetworkSettings": map[string]interface{}{
        "Networks": map[string]interface{}{
            "br1":    struct{}{},
            "bridge": struct{}{},
        },
    },
}

t := template.Must(template.New("").Parse("{{range $k, $v := .NetworkSettings.Networks}}{{println $k}}{{end}}"))

if err := t.Execute(os.Stdout, m); err != nil {
    panic(err)
}

Which outputs (try it on the Go Playground):

br1
bridge

So use the following command:

docker inspect network-test01 --format '{{range $k, $v := .NetworkSettings.Networks}}{{println $k}}{{end}}'

Also note that the docker command will also output a newline after each item, so calling println can be omitted:

docker inspect network-test01 --format '{{range $k, $v := .NetworkSettings.Networks}}{{$k}}{{end}}'
Related