如何获取未运行的 Docker 容器的退出代码

huangapple go评论123阅读模式
英文:

How to get exit code for Docker container that is not running

问题

我需要获取处于非运行状态的容器的退出代码。
我知道容器没有在运行,这个信息是从另一个来源获取的。

在Docker的Go SDK中,是否有一种方法可以获取退出代码,而无需等待容器处于特定状态?
例如,ContainerWaitWaitResponse提供了吗?

是否可以简单地使用我已经知道的容器状态调用ContainerWait作为解决方案?还是有更好的解决方案?

我特别希望避免使用ContainerWait,因为我可以看到这个调用非常耗费时间。
如果容器的状态是停止的,每个容器的调用大约需要10毫秒,如果容器处于重新启动状态,则需要20到50毫秒之间的时间。

英文:

I need to get the exit code for containers that are in none running state.
I know the container is not running, I get this information from a different source.

Is there a way in Docker's go SDK to get the exit code, without having to wait for the container to be in a certain state?
As for instance ContainerWait's WaitResponse provide?

Would it be an okay solution to simply call ContainerWait with the state that I already no the container is in? Or is there a better solution?

I am in particular interested in avoiding ContainerWait as I can see the call is quite expensive.
With the call consting ~10ms per container if its state is stopped and a between 20 and 50ms if the contianer is in the restarting state.

答案1

得分: 1

退出代码位于ContainerState结构中。它嵌入在来自(*Client).ContainerInspect()的响应中的State字段中。

例如:

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

  // 可能的值在`ContainerState`文档中列出;似乎没有为这些值定义命名常量。
  if inspection.State.Status != "exited" {
    return errors.New("容器未退出")
  }

  if inspection.State.ExitCode != 0 {
    return fmt.Errorf("容器以状态 %d 退出", inspection.State.ExitCode)
  }

  return nil
}
英文:

The exit code is in the ContainerState structure. This is embedded in a State field in the response from (*Client).ContainerInspect().

For example:

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
}

</details>



huangapple
  • 本文由 发表于 2023年4月24日 14:59:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76089286.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定