简体   繁体   中英

How to use docker cli in golang to create subnet

I'm trying to create a docker network for my application written in Golang.

I'm aware that I can use this NetworkCreate function , but I'm not sure how to specify the network option.

In the regular terminal console, I can just create the network with

docker network create -d bridge --subnet=174.3.12.5/16 mynet

But how to use the NetworkCreate() as an equivalent for this network creation?

package main

import (
    "context"
    "fmt"
    "github.com/docker/docker/api/types"
    "github.com/docker/docker/api/types/network"
    "github.com/docker/docker/client"
)

func main() {
    cli, err := client.NewClientWithOpts(client.FromEnv)
    if err != nil {
        fmt.Println(err)
    }

    newnetwork := types.NetworkCreate{IPAM: &network.IPAM{
        Driver: "default",
        Config: []network.IPAMConfig{network.IPAMConfig{
            Subnet: "174.3.12.5/16",
        }},
    }}

    res, err := cli.NetworkCreate(context.Background(), "test", newnetwork)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(res)

}

this is a minimal implementable example. the name for driver is default .

You can specify the network options via the NetworkCreate options struct.

If you want to convert the command docker network create -d bridge --subnet=174.3.12.5/16 mynet to a golang equivalent, It'll look something like this:

networkResponse, err := client.NetworkCreate(context.Background(), "mynet", types.NetworkCreate{
    Driver: "bridge",
    IPAM: &network.IPAM{
        Config: network.IPAMConfig{
            Subnet: "174.3.12.5/16",
        },
    },
})

You can use exec.Command(...).CombinedOutput()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM