我想在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”。
答案 0 :(得分:1)
用 ContainerExecAttach
代替 ContainerExecStartattach, err := dockerClient.ContainerExecAttach(ctx, idResponse.ID, config)
if err != nil {
return err
}
defer attach.Close()
go io.Copy(os.Stdout, attach.Reader)