Reputation: 3381
I want to compile untrusted code in docker container, so I want to test exec command
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. 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
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.
Upvotes: 1
Views: 3579
Reputation: 789
Instead of ContainerExecStart replace it with ContainerExecAttach
attach, err := dockerClient.ContainerExecAttach(ctx, idResponse.ID, config)
if err != nil {
return err
}
defer attach.Close()
go io.Copy(os.Stdout, attach.Reader)
Upvotes: 3