Golang Docker SDK: 获取容器运行时命令
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)
}
代码解释:
- 首先,导入必要的库:
fmt、github.com/docker/docker/api/types、github.com/docker/docker/client和context。 - 创建一个
context.Background()对象。 - 使用
client.NewClientWithOpts(client.FromEnv)创建一个 Docker 客户端对象。 - 设置容器 ID,并使用
cli.ContainerInspect(ctx, containerID)获取容器的详细信息。 - 从
containerJSON.Config.Cmd字段获取容器运行时的命令列表。 - 使用
fmt.Println(cmd)打印命令列表。
注意:
containerID替换为要获取命令的容器 ID。- 确保已安装 Docker 并配置好环境变量。
通过以上代码,您可以轻松地使用 Golang Docker SDK 获取容器运行时命令,并在您的应用程序中进行各种操作。
原文地址: https://www.cveoy.top/t/topic/fWyQ 著作权归作者所有。请勿转载和采集!