简体   繁体   English

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

[英]cannot get logs from docker container using golang docker sdk

I want to compile untrusted code in docker container, so I want to test exec command我想在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{})

} }

as you can see, I create an new exec process, exec a new cmd called "echo hello", I want to get output from running container and show in my golang console.如您所见,我创建了一个新的 exec 进程,执行了一个名为“echo hello”的新 cmd,我想从正在运行的容器中获取输出并显示在我的 golang 控制台中。 but not working, could you help me to solve?但不工作,你能帮我解决吗? I try so many ways but not worked.我尝试了很多方法但没有奏效。

and I also try to remove dockerClient.ContainerLogs block, replace with我也尝试删除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)

but still cannot get logs from container.但仍然无法从容器中获取日志。 When I run above code, my console is empty, expected result is have "hello" in my console.当我运行上面的代码时,我的控制台是空的,预期的结果是我的控制台中有“你好”。

Instead of ContainerExecStart replace it with ContainerExecAttachContainerExecAttach代替ContainerExecStart

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM