user5517392
user5517392

Reputation: 2369

How to check if the docker engine and a docker container are running?

In a script, I need to check:

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

Upvotes: 236

Views: 645006

Answers (20)

BMitch
BMitch

Reputation: 263459

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.

Upvotes: 226

Wizard.Ritvik
Wizard.Ritvik

Reputation: 11612

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

Upvotes: 0

ugate
ugate

Reputation: 101

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

Upvotes: 1

randomcontrol
randomcontrol

Reputation: 2282

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

Upvotes: 156

Josiah
Josiah

Reputation: 2866

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

Upvotes: 3

foo2bar
foo2bar

Reputation: 151

container status: true/false

# docker inspect --format '{{json .State.Running}}' container-name
true
#

Upvotes: 15

hagrawal7777
hagrawal7777

Reputation: 14658

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.

Upvotes: 8

yasir hasan
yasir hasan

Reputation: 87

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

Upvotes: 6

Emilia Tyl
Emilia Tyl

Reputation: 575

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.

Upvotes: 16

rilCy
rilCy

Reputation: 413

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

Upvotes: 26

ymmy
ymmy

Reputation: 193

docker ps -a

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

Upvotes: 9

Sachin Verma
Sachin Verma

Reputation: 3802

How I check in SSH.Run:

systemctl

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

Its a docker or WSL container.

Upvotes: 1

Senio Caires
Senio Caires

Reputation: 504

List all containers:

docker container ls -a

ls = list
-a = all

Check the column "status"

Upvotes: 39

DocJ457
DocJ457

Reputation: 877

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

Upvotes: 2

Marco Lackovic
Marco Lackovic

Reputation: 6487

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

Upvotes: 5

mrgnw
mrgnw

Reputation: 1788

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>

Upvotes: 2

Hernan Garcia
Hernan Garcia

Reputation: 1604

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 *

Upvotes: 32

Rajusekhar Alle
Rajusekhar Alle

Reputation: 121

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.

Upvotes: 10

Naanii
Naanii

Reputation: 197

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.

Upvotes: 10

Glen Pierce
Glen Pierce

Reputation: 4801

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.

Upvotes: 15

Related Questions