Skip to content

Instantly share code, notes, and snippets.

@jprinet
Created January 20, 2020 21:36
Show Gist options
  • Save jprinet/6389f5cb26b3e121a91e1a2454c38058 to your computer and use it in GitHub Desktop.
Save jprinet/6389f5cb26b3e121a91e1a2454c38058 to your computer and use it in GitHub Desktop.
wrapper script to launch command when dependency is ready
#!/bin/sh
readonly MAX_RETRY=10
readonly DELAY_BETWEEN_TRY_IN_SECONDS=10
readonly DEPENDENCY_CHECK_COMMAND=$1
readonly CONTAINER_RUN_COMMAND=$2
# wait until a command succeeds
#
# Usage: waitUntilReady "<command arg1...argN>"
function waitUntilReady() {
local count=0
local command=$1
while ! eval ${command}; do
count=$((${count} + 1))
if [[ ${count} -lt ${MAX_RETRY} ]]; then
echo "INFO - not ready, waiting ${DELAY_BETWEEN_TRY_IN_SECONDS} seconds (${count}/${MAX_RETRY})..."
sleep ${DELAY_BETWEEN_TRY_IN_SECONDS}
else
echo "ERROR - not ready, no more retries left."
return 1
fi
done
echo "INFO - ready!"
return 0
}
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <DEPENDENCY_CHECK_COMMAND> <CONTAINER_RUN_COMMAND>" >&2
exit 1
fi
echo "INFO - checking dependency status"
if ! waitUntilReady "${DEPENDENCY_CHECK_COMMAND}"; then
echo "ERROR - dependency not ready, stopping container"
exit 2
fi
echo "INFO - starting container"
${CONTAINER_RUN_COMMAND}
@jprinet
Copy link
Author

jprinet commented Jan 20, 2020

DB dependency:

ENV HEALTH_CHECK_COMMAND "curl --max-time 5 --silent --show-error --fail http://foo/bar/health"
ENV CONTAINER_RUN_COMMAND "my-command.sh"
ENTRYPOINT /bin/bash wait-until-ready.sh "${HEALTH_CHECK_COMMAND}" "${CONTAINER_RUN_COMMAND}"

Server dependency:

ENV HEALTH_CHECK_COMMAND "mysql -h dbhost -u dbuser -pdbpassword -D dbname -e 'SELECT 1'"
ENV CONTAINER_RUN_COMMAND "start-server.sh"
ENTRYPOINT /bin/bash wait-until-ready.sh "${HEALTH_CHECK_COMMAND}" "${CONTAINER_RUN_COMMAND}"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment