Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get exit code from docker entrypoint command

Tags:

bash

docker

I have a docker container that runs a script via the entrypoint directive. The container closes after the entrypoint script is finished. I need to get the exit code from the script in order to do some logging if the script fails. Right now I'm thinking of something like this

docker run container/myContainer:latest

if [ $? != 0 ];
then
    do some stuff
fi

Is this proper way to achieve this? Specifically, will this be the exit code of docker run or of my entrypoint script?

like image 406
David Stein Avatar asked Jul 24 '26 07:07

David Stein


2 Answers

Yes, the docker container run exit code is the exit code from your entrypoint/cmd:

$ docker container run busybox /bin/sh -c "exit 5"

$ echo $?
5

You may also inspect the state of an exited container:

$ docker container inspect --format '{{.State.ExitCode}}' \
    $(docker container ls -lq)
5
like image 103
BMitch Avatar answered Jul 26 '26 19:07

BMitch


Checking the value of $? is not needed if you just want to act upon the exit status of the previous command.

if docker run container/myContainer:latest; then
  do_stuff
fi

The above example will run/execute do_stuff if the exit status of docker run is zero which is a success.

You can add an else and elif clause in that

Or if you want to negate the exit status of the command.

if ! docker run container/myContainer:latest; then
  do_stuff
fi

The above example will run do_stuff if the exit status of docker run is anything but zero, e.g. 1 and going up, since the ! negates.

If the command has some output and if does not have a silent/quite flag/option you can redirect it to /dev/null

if docker run container/myContainer:latest >/dev/null; then
  do_stuff
fi
  • Should not output anything to stdout
  • see help test | grep -- '^[[:blank:]]*!'
  • In some cases if some output is still showing then that might be stderr which you can silent with >/dev/null 2>&1 instead of just >/dev/null
like image 25
Jetchisel Avatar answered Jul 26 '26 20:07

Jetchisel