从Docker SDK中的容器中获取输出

时间:2017-08-18 12:29:32

标签: docker go sdk

我正在尝试使用Docker SDK为golang运行容器,但我无法从容器中获取输出。我正在使用以下代码实际运行容器,但不会发回应用程序的stderr和stdout。你能告诉我做错了什么吗?

type dckr struct {
    cli      *client.Client
    username string
    password string
    addr     string
    ctx      context.Context
}

func (d *dckr) Run(containername string, image string, command []string, bind []string, stdout io.Writer, stderr io.Writer) error {
    log.Printf("[Create] %s -> %s \n", image, containername)

    res, err := d.cli.ContainerCreate(
        d.ctx,
        &container.Config{
            User:         "root",
            AttachStdout: true,
            AttachStderr: true,
            Image:        image,
            Cmd:          command,
        },
        &container.HostConfig{
            AutoRemove: true,
            Binds:      bind,
        },
        &network.NetworkingConfig{},
        containername,
    )

    if err != nil {
        log.Println("[Create] Failed. %s", err)
        return err
    }
    defer d.cli.ContainerRemove(d.ctx, res.ID, types.ContainerRemoveOptions{Force: true})

    log.Printf("[Create] id: %s \n", res.ID)
    for wrn := range res.Warnings {
        log.Printf("[Create] %s \n", wrn)
    }

    rsp, err := d.cli.ContainerAttach(d.ctx, containername, types.ContainerAttachOptions{
        Stream: false,
        Stdout: true,
        Stderr: true,
        Logs:   true,
    })

    if err != nil {
        log.Printf("[Attach] Fail. %s \n", err)
        return err
    }
    log.Printf("[Attach] %s", res.ID)
    defer rsp.Close()

    err = d.cli.ContainerStart(d.ctx, res.ID, types.ContainerStartOptions{})
    if err != nil {
        log.Printf("[Run] Fail. %s \n", err)
        return err
    }

    _, err = stdcopy.StdCopy(stdout, stderr, rsp.Reader)
    return err
}

0 个答案:

没有答案