如何通过Golang SDK获取docker api版本?

时间:2018-02-06 07:27:52

标签: docker go

当我必须使用NewEnvClient()创建Docker客户端时,我需要知道Docker守护程序API版本并设置DOCKER_API_VERSION的环境变量,否则我将收到错误:

Error response from daemon: client version 1.36 is too new. Maximum supported API version is 1.35

1 个答案:

答案 0 :(得分:0)

如果您在同一个docker主机中执行代码,则可以使用以下方法获取API版本。它执行docker version命令并从该输出中获取API版本。

package main

import (
    "os/exec"
    "bytes"
    "os"
    "github.com/docker/docker/client"
    "golang.org/x/net/context"
    "github.com/docker/docker/api/types"
    "strings"
)

func main() {
    cmd := exec.Command("docker", "version", "--format", "{{.Server.APIVersion}}")
    cmdOutput := &bytes.Buffer{}
    cmd.Stdout = cmdOutput

    err := cmd.Run()
    if err != nil {
        panic(err)
    }
    apiVersion := strings.TrimSpace(string(cmdOutput.Bytes()))
    // TODO: (optional) verify the api version is in the correct format(a.b)
    os.Setenv("DOCKER_API_VERSION", apiVersion)
    // execute docker commands
    ctx := context.Background()
    cli, err := client.NewEnvClient()
    if err != nil {
        panic(err)
    }
    _, err = cli.ImagePull(ctx, "alpine", types.ImagePullOptions{})
    if err != nil {
        panic(err)
    }
}