gpt4 book ai didi

api - 无法使用golang docker sdk从docker容器获取日志

转载 作者:行者123 更新时间:2023-12-01 22:18:31 25 4
gpt4 key购买 nike

我想在Docker容器中编译不受信任的代码,所以我想测试exec命令

import (
"context"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
log "github.com/sirupsen/logrus"
"io"
"os"
)

func main() {
dockerClient, err := client.NewClientWithOpts(client.WithVersion("1.38"))
if err != nil{
log.Error("error when create dockerClient ",err)
}

ctx := context.Background()

container, err := dockerClient.ContainerCreate(ctx,&container.Config{
Image:"golang",
OpenStdin:true,
Tty:true,
AttachStdin:true,
Cmd:[]string{"bash"},
AttachStdout:true,
AttachStderr:true,


},nil,nil,"")

if err := dockerClient.ContainerStart(ctx,container.ID,types.ContainerStartOptions{});err != nil{
log.Error("error when start container", err)
return
}

idResponse, err :=dockerClient.ContainerExecCreate(ctx,container.ID,types.ExecConfig{
Cmd:[]string{"echo","hello"},
Tty:true,
AttachStderr:true,
AttachStdout:true,
AttachStdin:true,
Detach:true,
})

if err := dockerClient.ContainerExecStart(ctx,idResponse.ID,types.ExecStartCheck{

}); err != nil{
log.Error("error when exec start ", err)
}

reader, err :=dockerClient.ContainerLogs(ctx,container.ID,types.ContainerLogsOptions{
ShowStdout:true,
ShowStderr:true,


})

if err != nil{
log.Error("error when containerLogs",err)
}

go io.Copy(os.Stdout,reader)

<- make(chan struct{})

}

如您所见,我创建了一个新的exec进程,执行了一个名为“echo hello”的新cmd,我想从运行容器中获取输出并显示在我的golang控制台中。但没有工作,您能帮我解决吗?我尝试了很多方法,但是没有用。

我也尝试删除 dockerClient.ContainerLogs块,替换为
conn, err :=dockerClient.ContainerAttach(ctx,container.ID,types.ContainerAttachOptions{
Stdout:true,
Stderr:true,
Stdin:true,
Stream:true,
Logs:true,
})

go io.Copy(os.Stdout,conn.Reader)

但仍然无法从容器中获取日志。当我运行上述代码时,控制台为空,预期结果是控制台中出现“hello”。

最佳答案

代替ContainerExecStart,将其替换为ContainerExecAttach

attach, err := dockerClient.ContainerExecAttach(ctx, idResponse.ID, config)
if err != nil {
return err
}
defer attach.Close()
go io.Copy(os.Stdout, attach.Reader)

关于api - 无法使用golang docker sdk从docker容器获取日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52145231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com