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?
20 Answers 20
If you are looking for a specific container, you can run:
if [ "$( docker container inspect -f '>' $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 '>' $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.
I use docker inspect -f ‘<>‘ $container_name since I start my container with a restart policy, though here «true» is what you want to avoid.
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 ‘<>‘ $ 2>/dev/null)» = «true» ]; then echo yup; else echo nope; fi
systemctl : The term ‘systemctl’ is not recognized as the name of a cmdlet, function, script file, or operable program
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
you can check docker state using: systemctl is-active docker
➜ ~ systemctl is-active docker active
➜ ~ 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 *
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 <>
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
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
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.
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.
container status: true/false
# docker inspect --format '>' container-name true #
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
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.
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.
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
This is exactly what I was looking for. And it works. (It’s good when people who vote something down say why, so noobs can learn better SO etiquette. 🙂 )
You can see all docker containers whether it is alive or dead.
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=>>» 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
Run this command in the terminal:
If docker is not running, you wil get this message:
Error response from daemon: dial unix docker.raw.sock: connect: connection refused
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
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
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 ($/$)" #This says that until docker inspect reports the container is in a running state, keep looping. until [[ $(docker inspect --format '>' $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 ($/$)" fi # Wait a second and increment the counter sleep 1s ((counter++)) done
If the underlying goal is «How can I start a container when Docker starts?»
To add a restart policy to an existing container:
docker update --restart=always
on a Mac you might see the image:
if you right click on the docker icon then you see:
If response: Failed to get D-Bus connection: Operation not permitted
Its a docker or WSL container.
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.
#!/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 > $1) fi if [[ $health2 != "healthy" ]]; then health2=$(docker inspect -f > $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
Docker посмотреть запущенные контейнеры, запустить или остановить контейнеры
Docker — это популярный инструмент виртуализации, который копирует конкретную операционную среду поверх основной ОС. Каждая среда называется контейнером. Управление контейнерами необходимо для работы в Docker.
Контейнер использует образ предварительно сконфигурированной операционной системы, оптимизированный для конкретной задачи. Когда образ Docker запущен, он существует в контейнере. Например, несколько контейнеров могут одновременно запускать один и тот же образ в одной операционной системе.
Список запущенных Docker контейнеров
Чтобы вывести список всех запущенных контейнеров Docker, введите в окне терминала следующее:
Как вы можете видеть, изображение выше указывает на отсутствие запущенных контейнеров.
Чтобы вывести список всех работающих и остановленных контейнеров, добавьте параметр –a :
Для вывода списка контейнеров по их идентификатору используйте параметр –aq :
Чтобы просмотреть общий размер файла каждого контейнера, используйте параметр –s :
Чтобы просмотреть список последних созданных контейнеров, используйте параметр –l :
Команда ps предоставляет несколько столбцов информации:
- Container ID — Уникальный буквенно-цифровой номер для каждого контейнера
- Image — Образ базовой операционной системы, на котором основан контейнер
- Command — команда, запустившая контейнер
- Created — Как давно был создан контейнер
- Status — Время работы или простои
- Ports — Указывает любые порты, перенаправляемые в контейнер для работы в сети.
- Name — Памятное имя, присвоенное программным обеспечением Docker
Как запустить Docker контейнер
Основная команда для запуска одного или нескольких остановленных контейнеров Docker docker start :
docker start [options] container_id
Вы можете указать контейнер, используя его имя или идентификатор (длинный или короткий).
Чтобы создать новый контейнер из образа и запустить его, используйте docker run :
docker run [options] image [command] [argument]
Если вы не определите имя для вновь созданного контейнера, он создаст случайное имя строки. Чтобы определить имя контейнера, используйте параметр ––name :