Bash, Docker: Check Container Existence and Status
Posted August 6, 2020 by Yaroslav Grebnov ‐ 3 min read
In software test automation, we often need to dynamically create test environments using docker-compose. If we do it with a script, one of the first steps we take is to check whether a Docker container with some given name exists and what is its current status. The examples below show how to implement such checks in Bash.
Check if a Docker container exists
Create and run a container ( I will use alpine:latest in my examples):
docker run -it --name testContainer alpine:latest ash
docker ps shows that the testContainer status is Up:
docker ps
A simplest implementation of the container check is the following:
if [ $( docker ps -a | grep testContainer | wc -l ) -gt 0 ]; then
echo "testContainer exists"
else
echo "testContainer does not exist"
fi
Output:
testContainer exists
The check consists of the following steps. We start by outputting a list of containers with any status, we search for a testContainer
text in the output and we count the resulting lines. If the number of lines is greater than zero, we output testContainer exists
. otherwise, we output testContainer does not exist
.
If you have several containers with similar names running at the same time, or you have a container with the name testContainer2
, the check above may work not as expected. In order to have more accurate results of the check, we will replace the grep by the docker ps command filter option:
if [ $( docker ps -a -f name=testContainer | wc -l ) -eq 2 ]; then
echo "testContainer exists"
else
echo "testContainer does not exist"
fi
Output:
testContainer exists
Here, we filter the list of containers with any status by the name testContainer
and count the resulting lines. Please note that as docker ps output has a header line, we compare the resulting number of lines with 2. This check provides more accurate results.
Check Docker container status
Now we will extend our container existence check by adding a step of getting the status of the container in question.
output=$( docker ps -a -f name=testContainer | grep testContainer 2> /dev/null )
if [[ ! -z ${output} ]]; then
echo "A container with a name: testContainer exists and has status: $( echo ${output} | awk '{ print $7 }' )"
else
echo "Container with a name: testContainer does not exist"
fi
Output:
A container with a name: testContainer exists and has status: Up
The docker ps output with the list of containers is stored in a variable output. If a container with the given name is available, the output contains only one line containing the container name. The containers list header line is suppressed. We are also filtering out the the stderr (it is sent to /dev/null). We do this because later we check the output variable value for emptiness. If the variable has a non-empty value, we proceed to getting the container status. We do this by using a simple awk command.