[英]How to use docker cli in golang to create subnet
I'm trying to create a docker network for my application written in Golang.我正在尝试为我用 Golang 编写的应用程序创建一个 docker 网络。
I'm aware that I can use this NetworkCreate
function , but I'm not sure how to specify the network option.我知道我可以使用这个
NetworkCreate
function ,但我不确定如何指定网络选项。
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?但是如何使用
NetworkCreate()
作为这个网络创建的等价物呢?
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
.驱动程序的名称是
default
。
You can specify the network options via the NetworkCreate
options struct.您可以通过
NetworkCreate
options 结构体指定网络选项。
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:如果要将命令
docker network create -d bridge --subnet=174.3.12.5/16 mynet
转换为 golang 等效命令,它看起来像这样:
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()
您可以使用
exec.Command(...).CombinedOutput()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.