在Docker中为docker golang api设置容器的端口

时间:2017-08-07 08:03:04

标签: docker go docker-api

我期待使用docker golang api

做类似这样的事情

cmd:docker run -t -i -p 8989:8080“image-name”/ bin / bash

我也在使用golang sdk https://github.com/moby/moby/clienthttps://godoc.org/github.com/moby/moby/client,我的docker api版本是1.30(客户端和服务器都是)

以下是我正在使用的代码

 package main

 import (
       "fmt"

       "github.com/docker/docker/client"
       "github.com/docker/docker/api/types"
       "github.com/docker/docker/api/types/container"
       "golang.org/x/net/context"
       "github.com/docker/go-connections/nat"
    //"github.com/docker/docker/vendor/github.com/docker/go-connections/nat"
)

func check(err error) {
   if err != nil {
       panic(err)
   }
}


func main(){
    ctx := context.Background()
cli, err := client.NewEnvClient()
check(err)


config := &container.Config{
Image : image-name,
ExposedPorts: nat.PortSet{
    "8080/tcp": struct{}{},
},
Cmd : [] string {"sh","-c","while true; do sleep always; done","/bin/bash"},
}

host_config := &container.HostConfig{
     PortBindings: nat.PortMap{
     "8080/tcp": []nat.PortBinding{
         {
             HostIP: "0.0.0.0",
             HostPort: "8989",
         },
      },
   },
}


  resp, err := cli.ContainerCreate(ctx,config,host_config, nil,"")
  check(err)


  if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); 
      err != nil {
        panic(err)
  }


}

编译此代码后,我收到以下错误

# command-line-arguments
src\main\createcontainer1.go:53: cannot use "github.com/docker/go-connections/nat".PortSet literal (type "github.com/docker/go-connections/nat".PortSet) as type "github.com/docker/docker/vendor/github.com/docker/go-connections/nat".PortSet in field value

src\main\createcontainer1.go:65: cannot use "github.com/docker/go-connections/nat".PortMap literal (type "github.com/docker/go-connections/nat".PortMap) as type "github.com/docker/docker/vendor/github.com/docker/go-connections/nat".PortMap in field value

如果有人知道可能是什么问题以及如何解决问题。 请回答它,因为我是docker的初学者。

2 个答案:

答案 0 :(得分:0)

这是一个关于vendor/工作原理的Golang问题。

删除嵌套的供应商目录:

rm -rf vendor/github.com/docker/docker/vendor

如果您使用glide,则在安装依赖项时应使用glide install -v

有关详细信息,请查看此报告的issue

答案 1 :(得分:-1)

我的OSX解决方案:

mv /Users/<user>/go/src/github.com/docker/docker/vendor/github.com/docker/go-connections/{nat,nat.old}