213

In a script, I need to check:

a) Is the docker engine running?
b) Given a container name, is that docker container running?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
user5517392
  • 2,139
  • 2
  • 10
  • 4

20 Answers20

207

If you are looking for a specific container, you can run:

if [ "$( docker container inspect -f '{{.State.Running}}' $container_name )" = "true" ]; then ...

To avoid issues with a container that is in a crash loop and constantly restarting from showing that it's up, the above can be improved by checking the Status field:

if [ "$( docker container inspect -f '{{.State.Status}}' $container_name )" = "running" ]; then ...

If you want to know if dockerd is running itself on the local machine and you have systemd installed, you can run:

systemctl show --property ActiveState docker

You can also connect to docker with docker info or docker version and they will error out if the daemon is unavailable.

zforgo
  • 2,508
  • 2
  • 14
  • 22
BMitch
  • 231,797
  • 42
  • 475
  • 450
  • how would you put the `docker inspect …` inside a `if` statement of a bash script? – François Romain Jul 05 '17 at 18:59
  • 20
    `if [ $(docker inspect -f '{{.State.Running}}' $container_name) = "true" ]; then echo yup; else echo nope; fi` – BMitch Jul 05 '17 at 22:09
  • Correction: "docker version" produces regular output even if docker is not running. "docker info" shows an error indicating that docker is not running. – VeganHunter Jul 16 '18 at 08:39
  • @VeganHunter `docker version` produces output, but it also generates an error. The return code will be 1, not 0, and there will be a line for the server side check stating "Cannot connect to the Docker daemon...". – BMitch Jul 16 '18 at 12:39
  • 2
    I use `docker inspect -f '{{.State.Restarting}}' $container_name` since I start my container with a restart policy, though here "true" is what you want to avoid. – stav meir May 22 '19 at 20:47
  • 7
    Both bash and docker will complain for the above `if` statement, when the container is not running. This hides the unwanted spew for the false case: `if [ "$(docker inspect -f '{{.State.Running}}' ${container_name} 2>/dev/null)" = "true" ]; then echo yup; else echo nope; fi` – Trevor May 29 '19 at 12:30
  • 1
    `systemctl : The term 'systemctl' is not recognized as the name of a cmdlet, function, script file, or operable program` – Marco Lackovic Oct 25 '19 at 11:07
  • 2
    @MarcoLackovic sounds like you missed the "you have systemd installed" part above. – BMitch Oct 25 '19 at 13:24
  • @BMitch 's command seems to not work on the newest version of docker (running containers names have some additional characters ) . I posted as an answer the script that works well for me on all stations at work :) – Emilia Tyl Mar 03 '20 at 14:00
132

I ended up using

docker info

to check with a bash script if docker engine is running.

EDIT: which can be used to fail your script if docker isn't running, like so:

#!/usr/bin/env bash
if ! docker info > /dev/null 2>&1; then
  echo "This script uses docker, and it isn't running - please start docker and try again!"
  exit 1
fi
Brad Parks
  • 66,836
  • 64
  • 257
  • 336
randomcontrol
  • 1,996
  • 1
  • 15
  • 11
34

List all containers:

docker container ls -a

ls = list
-a = all

Check the column "status"

J. Scott Elblein
  • 4,013
  • 15
  • 58
  • 94
Senio Caires
  • 454
  • 4
  • 6
31

you can check docker state using: systemctl is-active docker

➜  ~  systemctl is-active docker
active

you can use it as:

➜  ~  if [ "$(systemctl is-active docker)" = "active" ]; then echo "is alive :)" ; fi
is alive :)

➜  ~  sudo systemctl stop docker

➜  ~  if [ "$(systemctl is-active docker)" = "active" ]; then echo "is alive :)" ; fi
 * empty response *
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Hernan Garcia
  • 1,416
  • 1
  • 13
  • 24
  • This don't answer the question. _"to check with container name"_ – jens.klose Aug 21 '19 at 11:36
  • yeah it seems the question is ambiguous, to check if container is running you should use `docker ps --filter name=pattern`, then you can format the output to check only the status adding this flag: `--format {{.Status}}` – Hernan Garcia Aug 21 '19 at 13:50
  • 1
    This will tell you if `systemctl` *thinks* `docker` is running, but it will not actually check if docker REALLY is running. So the `docker info` command above is a better choice, IMHO – James Stevens Feb 15 '22 at 14:23
26

For OS X users (Mojave 10.14.3)

Here is what i use in my Bash script to test if Docker is running or not

# Check if docker is running
if ! docker info >/dev/null 2>&1; then
    echo "Docker does not seem to be running, run it first and retry"
    exit 1
fi
tripleee
  • 175,061
  • 34
  • 275
  • 318
rilCy
  • 413
  • 4
  • 11
  • 1
    I refactored this to remove the [`if [[ $? -ne 0 ]]` antipattern.](/questions/36313216/why-is-testing-to-see-if-a-command-succeeded-or-not-an-anti-pattern) – tripleee Aug 24 '20 at 04:27
15

Any docker command (except docker -v), like docker ps If Docker is running, you'll get some valid response, otherwise you'll get a message that includes "Is your docker daemon up and running?"

You can also check your task manager.

Glen Pierce
  • 4,401
  • 5
  • 31
  • 50
15

Sometimes you don't know the full container name, in this case this is what worked for me:

if docker ps | grep -q keyword
then 
    echo "Running!"
else
    echo "Not running!"
    exit 1
fi

We list all the running container processes (docker ps -a would show us also not running ones, but that's not what I needed), we search for a specific word (grep part) and simply fail if we did not find at least one running container whose name contains our keyword.

tripleee
  • 175,061
  • 34
  • 275
  • 318
Emilia Tyl
  • 565
  • 1
  • 5
  • 17
  • Refactored to remove a massive collection of [shell programming antipatterns.](http://www.iki.fi/era/unix/award.html#wc) – tripleee Aug 24 '20 at 04:28
12

container status: true/false

# docker inspect --format '{{json .State.Running}}' container-name
true
#
foo2bar
  • 121
  • 1
  • 2
  • 3
    Please add some explanation to your answer such that others can learn from it – Nico Haase Jan 27 '21 at 21:52
  • For anyone else following this, if you are looking for a health check on a container, this is good. It will return true if it's working – Craig Feb 05 '21 at 00:39
  • 2
    This does not seem to work anymore. "State" is not one of the keys in the JSOn that gets returned. Not seeing anything about running or health either. But it is up, and I am getting a JSON response. – Joe Flack Aug 03 '21 at 23:15
  • Works flawlessly – Omar Omeiri Dec 11 '21 at 19:10
9

You can check with this command systemctl status docker it will show the status of the docker. If you want to start you can use systemctl start docker instead of systemctl you can try also with service, service docker status and service docker start respectively.

ponury-kostek
  • 7,824
  • 4
  • 23
  • 31
Naanii
  • 187
  • 1
  • 3
  • 13
9

You can also check if a particular docker container is running or not using following command:

docker inspect postgres | grep "Running"

This command will check if for example my postgres container is running or not and will return output as "Running": true

Hope this helps.

Rajusekhar Alle
  • 111
  • 1
  • 3
9

docker ps -a

You can see all docker containers whether it is alive or dead.

ymmy
  • 193
  • 1
  • 8
8

For the answer to your first question refer to this answer - https://stackoverflow.com/a/65447848/4691279

For your second question - you can use command like docker ps --filter "name=<<<YOUR_CONTAINER_NAME>>>" to check whether a particular container is running or not.

  • If Docker and Container both are running then you will get output like below:

    $ docker ps --filter "name=nostalgic_stallman"
    
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES       
    9b6247364a03        busybox             "top"               2 minutes ago       Up 2 minutes                            nostalgic_stallman
    
  • If Docker is not running then you will get an error message saying docker daemon is not running.

  • If Docker running but Container is not running then you will not get the container name in the output of this command.

hagrawal7777
  • 14,103
  • 5
  • 40
  • 70
6

Run this command in the terminal:

docker ps

If docker is not running, you wil get this message:

Error response from daemon: dial unix docker.raw.sock: connect: connection refused

danday74
  • 52,471
  • 49
  • 232
  • 283
yasir hasan
  • 87
  • 1
  • 3
5

Run:

docker version

If docker is running you will see:

Client: Docker Engine - Community
 Version:           ...
 [omitted]

Server: Docker Engine - Community
 Engine:
  Version:          ...
 [omitted]

If docker is not running you will see:

Client: Docker Engine - Community
 Version:           ...
 [omitted]

Error response from daemon: Bad response from Docker engine
Marco Lackovic
  • 6,077
  • 7
  • 55
  • 56
  • 1
    For Windows users, if the engine is not running, you may also see an error like: **error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.35/info: open //./pipe/docker_engine** – Ayo I May 28 '21 at 04:07
3

I have a more fleshed out example of using some of the work above in the context of a Gitea container, but it could easily be converted to another container based on the name. Also, you could probably use the docker ps --filter capability to set $GITEA_CONTAINER in a newer system or one without docker-compose in use.

# Set to name or ID of the container to be watched.
GITEA_CONTAINER=$(./bin/docker-compose ps |grep git|cut -f1 -d' ')

# Set timeout to the number of seconds you are willing to wait.
timeout=500; counter=0
# This first echo is important for keeping the output clean and not overwriting the previous line of output.
echo "Waiting for $GITEA_CONTAINER to be ready (${counter}/${timeout})"
#This says that until docker inspect reports the container is in a running state, keep looping.
until [[ $(docker inspect --format '{{json .State.Running}}' $GITEA_CONTAINER) == true ]]; do

  # If we've reached the timeout period, report that and exit to prevent running an infinite loop.
  if [[ $timeout -lt $counter ]]; then
    echo "ERROR: Timed out waiting for $GITEA_CONTAINER to come up."
    exit 1
  fi

  # Every 5 seconds update the status
  if (( $counter % 5 == 0 )); then
    echo -e "\e[1A\e[KWaiting for $GITEA_CONTAINER to be ready (${counter}/${timeout})"
  fi

  # Wait a second and increment the counter
  sleep 1s
  ((counter++))

done
Josiah
  • 2,666
  • 5
  • 30
  • 40
2

on a Mac you might see the image:

enter image description here

if you right click on the docker icon then you see:

enter image description here

alternatively:

docker ps

and

docker run hello-world

J. Scott Elblein
  • 4,013
  • 15
  • 58
  • 94
DocJ457
  • 797
  • 7
  • 17
2

If the underlying goal is "How can I start a container when Docker starts?"

We can use Docker's restart policy

To add a restart policy to an existing container:

Docker: Add a restart policy to a container that was already created

Example:

docker update --restart=always <container>
mrgnw
  • 1,771
  • 2
  • 17
  • 19
1

How I check in SSH.Run:

systemctl

If response: Failed to get D-Bus connection: Operation not permitted

Its a docker or WSL container.

Sachin Verma
  • 3,712
  • 10
  • 41
  • 74
0

Checking for .State.Status, .State.Running, etc. will tell you if it's running, but it's better to ensure that the health of your containers. Below is a script that you can run that will make sure that two containers are in good health before executing a command in the 2nd container. It prints out the docker logs if the wait time/attempts threshold has been reached.

Example taken from npm sql-mdb.

#!/bin/bash
# Wait for two docker healthchecks to be in a "healthy" state before executing a "docker exec -it $2 bash $3"
##############################################################################################################################
# $1 Docker container name that will wait for a "healthy" healthcheck (required)
# $2 Docker container name that will wait for a "healthy" healthcheck and will be used to run the execution command (required)
# $3 The actual execution command that will be ran (required). When "npm_deploy", all tokens will be included in execution of
#     "npm run jsdoc-deploy" and "npm publish"
attempt=0
health1=checking
health2=checking
while [ $attempt -le 79 ]; do
  attempt=$(( $attempt + 1 ))
  echo "Waiting for docker healthcheck on services $1 ($health1) and $2 ($health2): attempt: $attempt..."
  if [[ health1 != "healthy" ]]; then
    health1=$(docker inspect -f {{.State.Health.Status}} $1)
  fi
  if [[ $health2 != "healthy" ]]; then
    health2=$(docker inspect -f {{.State.Health.Status}} $2)
  fi
  if [[ $health1 == "healthy" && $health2 == "healthy"  ]]; then
    echo "Docker healthcheck on services $1 ($health1) and $2 ($health2) - executing: $3"
    docker exec -it $2 bash -c "$3"
    [[ $? != 0 ]] && { echo "Failed to execute \"$3\" in docker container \"$2\"" >&2; exit 1; }
    break
  fi
  sleep 2
done
if [[ $health1 != "healthy" || $health2 != "healthy"  ]]; then
  echo "Failed to wait for docker healthcheck on services $1 ($health1) and $2 ($health2) after $attempt attempts"
  docker logs --details $1
  docker logs --details $2
  exit 1
fi
ugate
  • 81
  • 2
0

On Mac OS X (M1 chip) - I went with docker version over docker info, as it turns out to be slightly faster to call the former in my case, as shown below.

$ time ( docker info >/dev/null 2>&1 )
( docker info > /dev/null 2>&1; )  0.11s user 0.18s system 39% cpu 0.722 total
$ time ( docker version >/dev/null 2>&1 )
( docker version > /dev/null 2>&1; )  0.05s user 0.05s system 39% cpu 0.238 total

So, 238ms vs 722ms -- it's more than twice as fast to opt with docker version!

In my Bash script, I added this to check if the Docker daemon is running:

# Check if docker is running
if ! docker version >/dev/null 2>&1; then
    echo "Docker does not seem to be running, run it first and retry!"
    exit 1
fi
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53