廖前程
廖前程

Reputation: 101

how to get docker api version by SDK of Golang?

I need to know Docker Daemon API version and setup the environment variable of DOCKER_API_VERSION when I have to create Docker client with NewEnvClient(), if not I will get an error about:

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

Upvotes: 1

Views: 1417

Answers (2)

Manish
Manish

Reputation: 81

You can use ClientVersion function call to get the version, Whereas its better to negotiate the api version by using client.WithAPIVersionNegotiation() in NewClientWithOpts. In case you are interested in making a direct API call from your local you can use below command, it can give you much more details then api version.

curl  --unix-socket /var/run/docker.sock -H "Content-Type: application/json" -X GET "http://localhost/version" -H "X-Registry-Auth:<encoded key>" | jq '.ApiVersion'
"1.41"

Upvotes: 0

Anuruddha
Anuruddha

Reputation: 3245

If you are executing your code in the same docker host you can use the following approach to get the API version. It execute docker version command and get the API version from that output.

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)
    }
}

Upvotes: 1

Related Questions