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
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.
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.
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>
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.
How I check in SSH.Run:
systemctl
If response: Failed to get D-Bus connection: Operation not permitted
Its a docker or WSL container.