7

I would like to have a shell script that checks if a particular container is running.

For example, I might want to start the container if it's not already running, or query some piece of information about it like what ports are exposed.

2 Answers 2

11

The docker ps command takes a -f / --filter option to locate the desired container. To test if the container is running by name we might try

$ docker ps --filter "name=myapp" --filter "status=running"
CONTAINER ID   IMAGE               COMMAND   CREATED          STATUS          PORTS     NAMES
91959ed76e77   foo/barbaz:latest   "/init"   10 minutes ago   Up 10 minutes             myapp

If we just want the container ID, because we're going to pass it to another command like docker exec, we can use -q / --quiet:

$ docker ps --filter "name=myapp" --filter "status=running" --quiet
91959ed76e77

To just check whether it is running, we can see if the output is non-empty:

if [ -n "$(docker ps -f "name=myapp" -f "status=running" -q )" ]; then
    echo "the container is running!"
fi

Or if we want some other piece of information about it, --format:

$ docker ps -f "name=myapp" -f "status=running" --format "{{.Image}}"
foo/barbaz:latest
Sign up to request clarification or add additional context in comments.

Comments

7

You might also try using the docker inspect command which works well with myapp as the container's name ... or the container's id :

if [ "$(docker inspect myapp --format '{{.State.Status}}')" = "running" ]; then
    echo "the container is running!"
fi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.