以编程方式检查Docker容器进程是否以非零状态结束

以编程方式检查Docker容器进程是否以非零状态结束

本文介绍了以编程方式检查Docker容器进程是否以非零状态结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Go应用程序,该应用程序使用Go Docker SDK启动一些Docker容器。我需要检查容器的进程是否以零(成功)状态代码退出。

I'm working on a Go application which starts some Docker containers using Go Docker SDK. I need to check if containers' processes exit with zero (success) status code.

这是最小的工作示例:

package main

import (
    "context"
    "io"
    "log"
    "os"

    "github.com/docker/docker/api/types"
    "github.com/docker/docker/api/types/container"
    "github.com/docker/docker/client"
)

func main() {
    ctx := context.Background()

    cli, err := client.NewEnvClient()
    if err != nil {
        log.Fatal(err)
    }

    reader, err := cli.ImagePull(
        ctx,
        "docker.io/library/alpine",
        types.ImagePullOptions{},
    )
    if err != nil {
        log.Fatal(err)
    }
    io.Copy(os.Stdout, reader)

    resp, err := cli.ContainerCreate(ctx, &container.Config{
        Image: "alpine",
        Cmd:   []string{"sh", "-c", "echo hello world; return 1"},
        Tty:   true,
    }, nil, nil, "")
    if err != nil {
        log.Fatal(err)
    }

    err = cli.ContainerStart(
        ctx,
        resp.ID,
        types.ContainerStartOptions{},
    )
    if err != nil {
        log.Fatal(err)
    }

    statusCh, errCh := cli.ContainerWait(
        ctx,
        resp.ID,
        container.WaitConditionNotRunning,
    )
    select {
    case err := <-errCh:
        if err != nil {
            log.Fatal(err)
        }
    case <-statusCh:
    }

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

    io.Copy(os.Stdout, out)
}

当您可以看到,容器中的过程结束了h非零状态( sh -c echo hello world;返回1。)。但是,它不会记录任何致命错误,并且在构建和执行时仅显示 hello world

As you can see, the process in the container ends with non-zero status (sh -c "echo hello world; return 1"). However, it doesn't log any fatal errors and simply displays hello world when built and executed:

{"status":"Pulling from library/alpine","id":"latest"}
{"status":"Digest: sha256:7043076348bf5040220df6ad703798fd8593a0918d06d3ce30c6c93be117e430"}
{"status":"Status: Image is up to date for alpine:latest"}
hello world

如何使用Docker Go SDK检查容器进程是否以非零状态退出?

How can I check that container process exited with non-zero status using Docker Go SDK?

推荐答案

我认为您应该使用状态通道来获取退出代码,该错误通道似乎用于与docker守护进程通信时是否出现错误,请参见。

I think you should use the status channel to get the exit code. The error channel seems to be used to signal if there was an error while talking to the docker daemon, see https://godoc.org/github.com/docker/docker/client#Client.ContainerWait.

这对我有用:

select {
case err := <-errCh:
    if err != nil {
        log.Fatal(err)
    }
case status := <-statusCh:
    log.Printf("status.StatusCode: %#+v\n", status.StatusCode)
}

这篇关于以编程方式检查Docker容器进程是否以非零状态结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:37