How to get the numeric exit status of an exited docker container?

依然范特西╮ 提交于 2019-12-05 12:31:58

问题


When a container exits, docker ps -a shows its exit code (scroll

$ docker run ubuntu bash -c "exit 1"
CONTAINER ID   IMAGE    COMMAND              CREATED        STATUS                     PORTS                     NAMES
c2c769c4b9ef   ubuntu   "bash -c 'exit 1'"   6 seconds ago  Exited (1) 3 seconds ago                             happy_fermat

How do I get the numeric exit code programmatically, without error-prone grep-ing and cut-ing?


回答1:


Use docker inspect with templates:

$ docker inspect c2c769c4b9ef --format='{{.State.ExitCode}}'
1



回答2:


You can use echo:

$ docker run debian bash -c "exit 1"
$ echo $?
1

$ docker run debian bash -c "exit 0"
$ echo $?
0



回答3:


The exit status of docker run is the exit status of the contained command, except if there is a problem with Docker itself (in which case the status is 125) or the contained command could not be invoked (in which case the status is 126) or could not be invoked (in which case the status is 127).

Therefore when you execute docker run as a child process, you can retrieve the exit status as you would for any other child process:

  • In a C or C++ program, or other programming language giving access to the POSIX API, using waitpid().
  • In a POSIX like shell (which in practice means most Unix shells, including bash), as the content of the special $? variable immediately after completion of a docker run.
  • In Java, the value of Process.exitValue() for the Process you used to do docker run.

If you are using a Docker API, it should provide access to the exit status.

  • In Java using the Spotify Docker client, the value of ContainerExit.statusCode() of the ContainerExit object returned by docker.waitContainer().


来源:https://stackoverflow.com/questions/46300610/how-to-get-the-numeric-exit-status-of-an-exited-docker-container

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!