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

BashDocker

Bash Problem Overview


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"]

Bash Solutions


Solution 1 - Bash

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.

Solution 2 - Bash

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

Solution 3 - Bash

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 *

Solution 4 - Bash

List all containers:

docker container ls -a

ls = list
-a = all

Check the column "status"

Solution 5 - Bash

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

Solution 6 - Bash

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.

Solution 7 - Bash

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.

Solution 8 - Bash

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.

Solution 9 - Bash

container status: true/false

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

Solution 10 - Bash

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.

Solution 11 - Bash

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

Solution 12 - Bash

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.

Solution 13 - Bash

docker ps -a

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

Solution 14 - Bash

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

Solution 15 - Bash

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

Solution 16 - Bash

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:

https://stackoverflow.com/questions/26852321/docker-add-a-restart-policy-to-a-container-that-was-already-created

Example:

docker update --restart=always <container>

Solution 17 - Bash

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

Solution 18 - Bash

How I check in SSH.Run:

systemctl

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

Its a docker or WSL container.

Solution 19 - Bash

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser5517392View Question on Stackoverflow
Solution 1 - BashBMitchView Answer on Stackoverflow
Solution 2 - BashrandomcontrolView Answer on Stackoverflow
Solution 3 - BashHernan GarciaView Answer on Stackoverflow
Solution 4 - BashSenio CairesView Answer on Stackoverflow
Solution 5 - BashrilCyView Answer on Stackoverflow
Solution 6 - BashGlen PierceView Answer on Stackoverflow
Solution 7 - BashEmilia TylView Answer on Stackoverflow
Solution 8 - BashRajusekhar AlleView Answer on Stackoverflow
Solution 9 - Bashfoo2barView Answer on Stackoverflow
Solution 10 - BashNaaniiView Answer on Stackoverflow
Solution 11 - BashMarco LackovicView Answer on Stackoverflow
Solution 12 - BashhagrawalView Answer on Stackoverflow
Solution 13 - BashkimmyView Answer on Stackoverflow
Solution 14 - Bashyasir hasanView Answer on Stackoverflow
Solution 15 - BashJosiahView Answer on Stackoverflow
Solution 16 - BashmrgnwView Answer on Stackoverflow
Solution 17 - BashDavid OdhiamboView Answer on Stackoverflow
Solution 18 - BashSachin VermaView Answer on Stackoverflow
Solution 19 - BashugateView Answer on Stackoverflow