Skip to content

Instantly share code, notes, and snippets.

@bumbummen99
Last active January 28, 2023 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bumbummen99/ef531519842ba3ca6136f7a86e7bf515 to your computer and use it in GitHub Desktop.
Save bumbummen99/ef531519842ba3ca6136f7a86e7bf515 to your computer and use it in GitHub Desktop.
Simple script to wait for a certain output from a docker container. Useful for waiting for mysql user being created after the mysql container has been started and healthy
#!/usr/bin/env bash
#
# Simple script to wait for a certain output from a docker container.
# Useful for waiting for mysql user being created after the mysql
# container has been started and healthy
#
# Author: Patrick Henninger <privat@skyraptor.eu>
# License: GPL 3.0 (https://choosealicense.com/licenses/gpl-3.0/)
#
# Configure
CONTAINER_OR_SERVICE="$1"
NEEDLE="$2"
TIMEOUT="${3:-60}"
STEP_SECONDS=2
STEPS=$(($TIMEOUT/$STEP_SECONDS))
DOCKER_COMPOSE="$(which docker-compose)"
# Use docker compose v2 if v1 is not available
if [ -z "DOCKER_COMPOSE" ]; then
DOCKER_COMPOSE="docker compose"
fi
# Make sure the service or container is running before we start watching
if [ -n `$DOCKER_COMPOSE ps -q $CONTAINER_OR_SERVICE` ] && [ -n `docker ps -q --no-trunc | grep $($DOCKER_COMPOSE ps -q $CONTAINER_OR_SERVICE)` ]; then
echo "Detected service with name $CONTAINER_OR_SERVICE"
elif [ "$( docker container inspect -f '{{.State.Status}}' $CONTAINER_OR_SERVICE )" == "running" ]; then
echo "Detected container with name $CONTAINER_OR_SERVICE"
else
echo "No running service or container with name \"$CONTAINER_OR_SERVICE\" could be found."
exit 1
fi
echo "Waiting for log output: \"$NEEDLE\"..."
# Run for amount of steps instead of while/until to provide timeout functionality
for i in $(seq 1 $STEPS)
do
# Break the execution if we have no more steps i.e. timeout
if [ "$i" -gt "$STEPS" ]; then
echo "Could not find needle \"$NEEDLE\" in haystack. Timed out after $TIMEOUT seconds."
exit 1
fi
# Check if the log contains the needle
if [ `$DOCKER_COMPOSE logs $CONTAINER_OR_SERVICE | grep -q "$NEEDLE"` ]; then
echo "Found \"$NEEDLE\" in haystack after $i*$STEP_SECONDS seconds."
exit
else
sleep $STEP_SECONDS
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment