Skip to content

Instantly share code, notes, and snippets.

@silveimar
Created May 29, 2020 22:33
Show Gist options
  • Save silveimar/8355d3ad6cb42bbc4fe47e95ea526a38 to your computer and use it in GitHub Desktop.
Save silveimar/8355d3ad6cb42bbc4fe47e95ea526a38 to your computer and use it in GitHub Desktop.
Wait for healthy container - for docker-compose started containers
#!/bin/bash
. "scripts/common.sh"
container=$1
timeout=${2:-30}
wait=${3:-500}
interval=$(echo "scale=2; $wait/1000"|bc -l);
printHelp() {
echo
echo "HELP for 'wait-for-healthy-container.sh'"
echo "usage:"
echo "./wait-for-healthy-container.sh <container name> <seconds to wait> <milliseconds between retries>"
echo "The final two options, wait & retry, are optional and will default to 30 & 500 respectively."
echo
exit 0
}
if [ -z "$container" ] || [ "$container" == "help" ] || [ "$container" == "-h" ] || [ "$container" == "-?" ] || [ "$container" == "--h" ]
then
printHelp
fi
log "\033[94m Waiting up to $timeout seconds for container: $container to be healthy. \033[0m"
checkForStatus(){
printf "."
result=`docker ps --filter 'health=healthy' --filter "name=$container" --format '{{.Names}}'`
if [[ "$result" == "$container" ]]
then
found="true"
fi
}
start=$SECONDS
run="true"
found="false"
while [ "$run" = "true" ]
do
checkForStatus
if [[ "$found" == "true" ]]
then
run="false"
echo
log "\033[94m $container is ready after $SECONDS seconds. \033[0m"
fi
sleep $interval
if (( $SECONDS > $timeout))
then
run="false"
echo
log "\033[31m ERROR: Timeout occurred after waiting $timeout seconds for $container. \033[0m"
exit -5
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment