登录
首页 >  Golang >  Go问答

获得未启动的Docker容器的退出状态码的方法

来源:stackoverflow

时间:2024-02-14 21:09:22 292浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《获得未启动的Docker容器的退出状态码的方法》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

我需要获取处于非运行状态的容器的退出代码。 我知道容器没有运行,我从不同的来源获取此信息。

Docker的go SDK中有没有一种方法可以获取退出代码,而不必等待容器处于某种状态? 比如ContainerWaitWaitResponse提供了什么?

在我已经不存在容器的状态下简单地调用 ContainerWait 是一个好的解决方案吗?或者有更好的解决方案吗?

我对避免 ContainerWait 特别感兴趣,因为我可以看到该调用非常昂贵。 如果容器的状态已停止,则每个容器的调用 consting 大约需要 10 毫秒;如果容器处于重新启动状态,则调用 consting 需要 20 到 50 毫秒。


正确答案


退出代码位于 containerstate 结构。这嵌入在 响应中的 state 字段中(*client).containerinspect().

例如:

func checkExitStatus(ctx context.Context, client *client.Client, containerID string) error {
  inspection, err := client.ContainerInspect(ctx, containerID)
  if err != nil {
    return err
  }

  // Possible values are listed in the `ContainerState` docs; there do not
  // seem to be named constants for these values.
  if inspection.State.Status != "exited" {
    return errors.New("container is not exited")
  }

  if inspection.State.ExitCode != 0 {
    return fmt.Errorf("container exited with status %d", inspection.State.ExitCode)
  }

  return nil
}

本篇关于《获得未启动的Docker容器的退出状态码的方法》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>