Search code examples
dockergoexit-code

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


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.


Solution

  • 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
    }