Context
I have a script that gets the status of GitLab inside a Docker container. Since the script does not know in advance whether the docker and accompanying container are running, I would like to first check if the Docker is up and running.
However, my current script runs:
# Write docker container command output to file.
output=$(sudo docker ps -a | sudo tee "$log_filepath")
And if that command returns some containers I parse the container ID from that output.
Issue
If the docker is not up and running successfully, the
sudo docker ps -a
returns:
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
with exit state ($?):
1: command not found
Approach
I would like to prevent this error, by safely checking if there are any containers up and running in docker. So the first thing I tried was:
sudo docker status
however, that is not a valid command.
Based on this answer it seems
systemctl show --property ActiveState docker
may safely show the docker state. However, I have not yet been able to verify whether it changes to active in case the docker is up and running due to other errors, nor have I been able to determine whether ActiveState=active implies the sudo docker ps -a command succeeds (in nominal cases).
Question
Hence, I would like to ask: *How can one safely run sudo docker ps -a, or otherwise safely determine there are no docker containers running?