Background
I use Docker (docker-compose) to built system for my local development and testing on Github Actions. In my local, I can check by my eyes if my containers have booted. However, in Github Actions, I need a way to make sure that my docker containers have booted and run test for the containers after their boot. Simply I came up with the following Github Actions setting. But usually that does not work because the completion of docker-compose up -d
does not mean the program / servers in the containers are ready.
jobs:
all:
name: My test
runs-on: ubuntu-18.04
steps:
- name: Docker compose up
run: docker-compose up -d
- name: Test
# run test for my containers. e.g. Access API servers
run: ...
Solution: Script to check health
I wrote the following bash script to check my target container health status. My docker-compose has healthcheck setting (see this article to learn how to setup). It checks the health every second and finishes its process after the container gets healthy. If the program did not get healthy within the timeout, the script exits with 1.
# Name of the target container to check
container_name="$1"
# Timeout in seconds. Default: 60
timeout=$((${2:-60}));
if [ -z $container_name ]; then
echo "No container name specified";
exit 1;
fi
echo "Container: $container_name";
echo "Timeout: $timeout sec";
try=0;
is_healthy="false";
while [ $is_healthy != "true" ];
do
try=$(($try + 1));
printf "■";
is_healthy=$(docker inspect --format='{{json .State.Health}}' $container_name | jq '.Status == "healthy"');
sleep 1;
if [[ $try -eq $timeout ]]; then
echo " Container did not boot within timeout";
exit 1;
fi
done
This is the command to run the script.
healthcheck.sh <container_id|name> <timeout_in_sec>
A realistic command should be like this. Waits 120
seconds or less until api
container gets ready. Then run test.sh
(Please change whatever command you want).
healthcheck.sh api 120 && test.sh
Finally, my Github Actions got the form like this.
jobs:
all:
name: My test
runs-on: ubuntu-18.04
steps:
- name: Docker compose up
run: docker-compose up -d
- name: Test
run: healthcheck.sh api 120 && test.sh
Appendix: Fix the name of a container
Without an explicit name, docker-compose names a container like api_1
to fix the name as you want, you must specify a name as container_name
in docker-compose.yml
.
services:
api:
container_name: api
Top comments (0)