基本上我需要这样的东西
docker run -p something:something --name xxxx imagename
在用于 docker api 的 golang sdk(这个 https://docs.docker.com/engine/api/sdks/)中,我当前的代码如下所示
exposedPorts, portBindings, _ := nat.ParsePortSpecs([]string{
"127.0.0.1:8080:2368",
})
// Running the ghost container
createdBody, err := dockerClient.ContainerCreate(context.Background(),
&container.Config{
Image: "ghost:latest",
ExposedPorts: exposedPorts,// it supposed to be nat.PortSet
},
&container.HostConfig{
PortBindings: portBindings,// it supposed to be nat.PortMap
},
&network.NetworkingConfig{},
containerName)
我正在使用这个 https://github.com/docker/go-connections/blob/master/nat/nat.go#L126 ParsePortSpecs 函数返回 (map[Port]struct{}, map[Port][]PortBinding, error) 但失败,因为 container.Config.ExposedPorts 是 nat.PortSet(它实际上是 map[Port]struct{} tho)和容器.HostConfig.PortBindins 是 nat.PortMap
我不确定是否要使用此客户端 https://github.com/fsouza/go-dockerclient因为我当前的 docker API 版本是 1.25 并且它不支持 1.23 以上的 API 版本
Best Answer-推荐答案
Docker Client Go SDK 自 1 月以来可能发生了一些变化,但我刚刚开始工作,所以我会记录我在这里所做的事情。
如果你需要一个暴露的端口,它看起来像 4140/tcp 在 PORTS 下 docker ps 那么您可以执行以下操作:
config := &container.Config{
Image: "nginx",
ExposedPorts: nat.PortSet{
"4140/tcp": struct{}{},
},
}
hostConfig := &container.HostConfig{}
ctx := context.Background()
containerResp, err := Docker.ContainerCreate(ctx, config, hostConfig, nil, "")
if err != nil {
panic(err)
}
if err := Docker.ContainerStart(ctx, containerResp.ID, types.ContainerStartOptions{}); err != nil {
panic(err)
}
如果你想将该端口绑定(bind)到 0.0.0.0 上的主机,它看起来像 0.0.0.0:4140->4140/tcp 在 PORTS 下 docker ps 您需要将端口绑定(bind)添加到 hostConfig:
config := &container.Config{
Image: "nginx",
ExposedPorts: nat.PortSet{
"4140/tcp": struct{}{},
},
}
hostConfig := &container.HostConfig{
PortBindings: nat.PortMap{
"4140/tcp": []nat.PortBinding{
{
HostIP: "0.0.0.0",
HostPort: "4140",
},
},
},
}
ctx := context.Background()
containerResp, err := Docker.ContainerCreate(ctx, config, hostConfig, nil, "")
if err != nil {
panic(err)
}
if err := Docker.ContainerStart(ctx, containerResp.ID, types.ContainerStartOptions{}); err != nil {
panic(err)
}
希望这会为某人节省一些时间
关于go - 在 docker api 的 golang sdk 中为 ContainerCreate 函数设置 PortBindings 配置,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/41789083/
|