skip to Main Content

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?

3

Answers


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

    Login or Signup to reply.
  2. 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",
            },
        },
    })
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search