Golang Docker SDK: 获取容器运行时命令

使用 Golang Docker SDK 中的 types.ContainerJSON 结构体可以轻松获取容器运行时命令。本文提供代码示例,演示如何通过访问 Config.Cmd 字段获取容器启动时的命令列表。

import (
	"fmt"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
	"context"
)

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

	containerID := 'your-container-id'
	containerJSON, err := cli.ContainerInspect(ctx, containerID)
	if err != nil {
		panic(err)
	}

	cmd := containerJSON.Config.Cmd
	fmt.Println(cmd)
}

代码解释:

  1. 首先,导入必要的库:fmtgithub.com/docker/docker/api/typesgithub.com/docker/docker/clientcontext
  2. 创建一个 context.Background() 对象。
  3. 使用 client.NewClientWithOpts(client.FromEnv) 创建一个 Docker 客户端对象。
  4. 设置容器 ID,并使用 cli.ContainerInspect(ctx, containerID) 获取容器的详细信息。
  5. containerJSON.Config.Cmd 字段获取容器运行时的命令列表。
  6. 使用 fmt.Println(cmd) 打印命令列表。

注意:

  • containerID 替换为要获取命令的容器 ID。
  • 确保已安装 Docker 并配置好环境变量。

通过以上代码,您可以轻松地使用 Golang Docker SDK 获取容器运行时命令,并在您的应用程序中进行各种操作。


原文地址: https://www.cveoy.top/t/topic/fWyQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录