skip to Main Content

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


  1. Chosen as BEST ANSWER

    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
    

  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search