如何通过golang获取容器ID

zih*_* li 3 go docker

我使用 golang 来开发应用程序。我想在应用程序中获取容器。我厌倦了 shell。但我想通过 go 获取容器。谢谢

Her*_*cia 6

您可以使用 docker/client
https://godoc.org/github.com/docker/docker/client

示例代码:

# listcontainers.go

package main

import (
    "context"
    "fmt"

    "github.com/docker/docker/api/types"
    "github.com/docker/docker/client"
)

func main() {
    cli, err := client.NewClientWithOpts(client.FromEnv)
    if err != nil {
        panic(err)
    }

    containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
    if err != nil {
        panic(err)
    }

    for _, container := range containers {
        fmt.Printf("%s %s\n", container.ID[:10], container.Image)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样执行

DOCKER_API_VERSION=1.35 go run listcontainers.go
Run Code Online (Sandbox Code Playgroud)

有关 docker 引擎 SDK 和 API 的更多信息
https://docs.docker.com/develop/sdk/