首页 > 解决方案 > golang如何获取容器ID

问题描述

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

标签: dockergo

解决方案


您可以使用 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)
    }
}

然后像这样执行

DOCKER_API_VERSION=1.35 go run listcontainers.go

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


推荐阅读