在使用 Golang Docker SDK 的 ContainerAttach 方法时,可以通过判断返回的 error 是否为 io.EOF 来判断容器是否结束。当容器结束时,会发送一个 EOF 信号,因此如果返回的 error 为 io.EOF,则表示容器已经结束。

示例代码如下:

ctx := context.Background()
container, err := cli.ContainerCreate(ctx, cfg, hostCfg, netCfg, nil, name)
if err != nil {
    log.Fatal(err)
}
if err := cli.ContainerStart(ctx, container.ID, types.ContainerStartOptions{}); err != nil {
    log.Fatal(err)
}

resp, err := cli.ContainerAttach(ctx, container.ID, types.ContainerAttachOptions{Stream: true, Stdin: false, Stdout: true, Stderr: true})
if err != nil {
    log.Fatal(err)
}
defer resp.Close()

go func() {
    _, err := io.Copy(os.Stdout, resp.Reader)
    if err != nil && !strings.Contains(err.Error(), 'use of closed network connection') {
        log.Fatal(err)
    }
}()

// 等待容器结束
_, err = cli.ContainerWait(ctx, container.ID)
if err != nil {
    log.Fatal(err)
}

// 容器已经结束
Golang Docker SDK ContainerAttach 方法判断容器结束

原文地址: https://www.cveoy.top/t/topic/kVdg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录