英文:
How to use docker cli in golang to create subnet
问题
我正在尝试为我用Golang编写的应用程序创建一个Docker网络。
我知道可以使用这个NetworkCreate
函数,但我不确定如何指定网络选项。
在常规终端控制台中,我可以使用以下命令创建网络:
docker network create -d bridge --subnet=174.3.12.5/16 mynet
但如何使用NetworkCreate()
函数来等效地创建这个网络呢?
英文:
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?
答案1
得分: 1
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)
}
这是一个最小可实现的示例。驱动程序的名称是 default
。
英文:
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
.
答案2
得分: 0
您可以通过NetworkCreate
选项结构来指定网络选项。
如果您想将命令docker network create -d bridge --subnet=174.3.12.5/16 mynet
转换为等效的Go语言代码,可以像这样编写:
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 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",
},
},
})
答案3
得分: -2
你可以使用exec.Command(...).CombinedOutput()
。
英文:
You can use exec.Command(...).CombinedOutput()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论