代码之家  ›  专栏  ›  技术社区  ›  Scott Stensland

我能把DockerAPI版本固定下来吗:客户端版本1.38太新了。最大支持API版本为1.37

  •  11
  • Scott Stensland  · 技术社区  · 6 年前

    有没有办法使用golang客户端来固定docker api版本?(未使用 dep for vendoring )

    下面的代码失败

    client version 1.38 is too new. Maximum supported API version is 1.37
    

    这段代码一直运行到最近

    go version go1.9.5 linux/amd64
    

    这里是: docker version

    Client:
     Version:      18.05.0-ce
     API version:  1.37
     Go version:   go1.9.5
     Git commit:   f150324
     Built:        Wed May  9 22:16:25 2018
     OS/Arch:      linux/amd64
     Experimental: false
     Orchestrator: swarm
    
    Server:
     Engine:
      Version:      18.05.0-ce
      API version:  1.37 (minimum version 1.12)
      Go version:   go1.9.5
      Git commit:   f150324
      Built:        Wed May  9 22:14:32 2018
      OS/Arch:      linux/amd64
      Experimental: false
    

    这会导致api版本不匹配

    package main
    
    // kill off some containers
    
    import (
        "fmt"
    
        "github.com/docker/docker/api/types"
        "github.com/docker/docker/client"
        "golang.org/x/net/context"
    
        "strings"
    )
    
    func main() {
        ctx := context.Background()
        cli, err := client.NewEnvClient()
        if err != nil {
            panic(err) // <--- crashes here due to API mismatch
        }
    
        containers, err := cli.ContainerList(ctx, types.ContainerListOptions{})
        if err != nil {
            panic(err)
        }
    
        for _, container := range containers {
    
            if strings.Contains(container.Image, "enduser") || strings.Contains(container.Image, "admin") {
    
                fmt.Println("\n we found enduser or admin so lets stop it\n")
    
                fmt.Print("Stopping container ", container.ID[:10], "... ")
                if err := cli.ContainerStop(ctx, container.ID, nil); err != nil {
                    panic(err)
                }
                fmt.Println("Success")
            }
        }
    }
    

    在英语中,上述错误是因为github repo客户端库的默认客户端版本比docker支持的版本新…所以要处理注释-解决方案是请求较低版本的repo库来匹配docker,而不是请求较高版本

    1 回复  |  直到 5 年前
        1
  •  24
  •   zero298    6 年前

    你可以要求一个特别的版本 NewClientWithOpts() 是的。

    package main
    
    import (
        "net/http"
    
        "github.com/docker/docker/api/types/container"
        "github.com/docker/docker/client"
        "golang.org/x/net/context"
    )
    
    func main() {
        ctx := context.Background()
        cli, err := client.NewClientWithOpts(client.WithVersion("1.37"))
        if err != nil {
            panic(err)
        }
    }
    

    Versioned API and SDK 是的。在最后,它使用go api并(尝试)链接到相关代码:

    可以通过以下方式之一指定要使用的API版本:

    文档硬链接到 master 分支可能已更改,但上面的代码应为您提供足够的上下文来理解。

        2
  •  3
  •   Henry Blyth    5 年前

    我有完全相同的问题,“Zoo929的回答对我来说完全适用。”

    然后我发现 client.WithAPIVersionNegotiation() 这也奏效了!

    如果您不需要固定版本,只希望代码与您的计算机运行的任何版本一起工作,我认为此选项将满足您的需要。