David Stein
David Stein

Reputation: 399

Get exit code from docker entrypoint command

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?

Upvotes: 7

Views: 10566

Answers (2)

BMitch
BMitch

Reputation: 263469

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

Upvotes: 8

Jetchisel
Jetchisel

Reputation: 7781

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

Upvotes: 3

Related Questions