Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Docker Tip #22: Checking the Exit Code of Stopped Containers

docker-tips-and-tricks.jpg

Once in a while, you may want to check the exact exit code of a stopped container. Here's how to do it.

Quick Jump:

It’s occasionally beneficial to know if your container exit correctly (without errors), or with a specific error. This may help you debug pesky problems.

Create a test container to emulate a generic error:
docker container run alpine sh -c "exit 1"

Running the above command should exit without any terminal output.

Verify the container was created and then stopped:
$ docker container ls -a

CONTAINER ID   IMAGE    COMMAND            CREATED              STATUS
61c688005b3a   alpine   "sh -c 'exit 1'"   About a minute ago   Exited (1) 3 seconds ago

The important bit here is the STATUS output which says it stopped with an exit code of 1. That’s the generic exit code for an error. Typically every code other than 0 is considered an error. 0 means the program stopped correctly without errors.

This is useful to know in the real world because if you’re writing your own scripts, you can automate things based on whether or not a container stopped successfully or not.

You can even get the exit code without any extra cruft by running docker inspect 61c6 --format='{{.State.ExitCode}}'. That’s perfect for scripts because you can check the code easily.

Free Intro to Docker Email Course

Over 5 days you'll get 1 email per day that includes video and text from the premium Dive Into Docker course. By the end of the 5 days you'll have hands on experience using Docker to serve a website.



Comments