dqf98772 2018-01-22 23:42
浏览 467
已采纳

如何通过WebSocket获取Docker容器输出?


I am trying to send output from a docker container to the console using fmt, but when trying to do it i get this.

&{0xc0422a65c0 {0 0} false <nil> 0x6415a0 0x641540}

How do I do this? This is my full code.

func main() {
    imageName := "hidden/hidden"

ctx := context.Background()

cli, err := client.NewClient("tcp://0.0.0.0:0000", "v0.00", nil, nil)
if err != nil {
    panic(err)
}

fmt.Println("Pulling \"" + imageName + "\"")
_, err = cli.ImagePull(ctx, imageName, types.ImagePullOptions{})
if err != nil {
    panic(err)
}

containerConfig := &container.Config{
    Image: imageName,
    Cmd: []string{"./app/start.sh", "--no-wizard"},
}

resp, err := cli.ContainerCreate(ctx, containerConfig, nil, nil, "")
if err != nil {
    panic(err)
}

if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
    panic(err)
}

timer := time.NewTimer(time.Minute)
go func() {
    <-timer.C
    if err := cli.ContainerStop(ctx, resp.ID, nil); err != nil {
        panic(err)
    }
}()

out, err := cli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true, ShowStderr: true, Follow: true})
if err != nil {
    panic(err)
}

io.Copy(os.Stdout, out) // This is what I want to change to print with "fmt".
}

Tried: (but does not display until container is done.)

buf := new(bytes.Buffer)
buf.ReadFrom(out)
fmt.Println(buf.String())

Intention: Allow real-time console output to the web.

  • 写回答

2条回答 默认 最新

  • duancenxie2233 2018-01-23 13:52
    关注

    This seems to be the answer to my question, I did some searching about scanners as Cerise Limón commented. Anyone else who seems to be having the issue that I did can use this code. Thanks to all that helped.

    scanner := bufio.NewScanner(out)
    scanner.Split(bufio.ScanLines)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?