181

In a script, I need to check:

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

[the initial wording of this question was ambiguous, with some people interpreting it as "check docker engine", and others as "check docker container"]

Rob Bednark
  • 22,937
  • 20
  • 77
  • 112
user5517392
  • 1,819
  • 2
  • 9
  • 4

19 Answers19

178

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.

BMitch
  • 188,157
  • 34
  • 411
  • 383
  • how would you put the `docker inspect …` inside a `if` statement of a bash script? – François Romain Jul 05 '17 at 18:59
  • 17
    `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
  • 4
    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
97

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
  • 60,289
  • 61
  • 245
  • 309
randomcontrol
  • 1,520
  • 12
  • 9
28

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
  • 330,190
  • 66
  • 504
  • 555
Hernan Garcia
  • 1,262
  • 1
  • 11
  • 22
  • 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
  • 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
28

List all containers:

docker container ls -a

ls = list
-a = all

Check the column "status"

J. Scott Elblein
  • 3,541
  • 11
  • 52
  • 82
Senio Caires
  • 394
  • 3
  • 6
25

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
  • 158,107
  • 27
  • 234
  • 292
rilCy
  • 393
  • 3
  • 10
  • 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
  • 3,755
  • 5
  • 31
  • 46
13

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
  • 158,107
  • 27
  • 234
  • 292
Emilia Tyl
  • 393
  • 4
  • 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
10

container status: true/false

# docker inspect --format '{{json .State.Running}}' container-name
true
#
foo2bar
  • 101
  • 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
  • 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 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
6

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,355
  • 4
  • 20
  • 28
Naanii
  • 161
  • 1
  • 3
  • 12
6

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
  • 5,350
  • 5
  • 53
  • 51
  • 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
6

docker ps -a

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

kimmy
  • 85
  • 1
  • 5
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
  • 45,909
  • 39
  • 198
  • 245
yasir hasan
  • 105
  • 1
  • 3
6

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.

hagrawal
  • 13,141
  • 5
  • 38
  • 63
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,238
  • 4
  • 26
  • 35
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,753
  • 2
  • 16
  • 18
1

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
  • 3,541
  • 11
  • 52
  • 82
David Odhiambo
  • 629
  • 6
  • 14
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,544
  • 9
  • 35
  • 70
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
  • 36
  • 1