Skip to content

Instantly share code, notes, and snippets.

@tkhduracell
Last active October 29, 2022 11:59
Show Gist options
  • Save tkhduracell/4de5828bcd0235ad31c92ae71945d117 to your computer and use it in GitHub Desktop.
Save tkhduracell/4de5828bcd0235ad31c92ae71945d117 to your computer and use it in GitHub Desktop.
Await container start healthy (smoke test)
#!/bin/sh
set -e pipefail
#
# Assuming container has HEALTHCHECK command specified.
# Example:
# HEALTHCHECK --interval=1s --timeout=1s --start-period=3s --retries=30 \
# CMD curl --fail http://localhost:80/ || exit 1
#
CONTAINER_IMAGE=${CONTAINER_IMAGE:-eu.gcr.io/org/image1:latest}
CONTAINER_NAME=${CONTAINER_NAME:-frontend}
MAX_TRIES=${MAX_TRIES:-30}
SUCCESS=0
exit_hook(){
if [ ${SUCCESS} = 1 ]; then
echo "Container started successfully! (exit 0)"
fi
if [ ${SUCCESS} = 0 ]; then
printf "\nContainer failed to start!"
printf "\nContainer logs: "
docker logs "${CONTAINER_NAME}"
printf "\nContainer status: "
docker inspect --format='{{json .State}}' "${CONTAINER_NAME}"|jq
fi
docker stop "${CONTAINER_NAME}" >/dev/null 2>&1 || true
docker rm "${CONTAINER_NAME}" >/dev/null 2>&1 || true
}
docker stop "${CONTAINER_NAME}" >/dev/null 2>&1 || true
docker rm "${CONTAINER_NAME}" >/dev/null 2>&1 || true
docker run --name "${CONTAINER_NAME}" -d "${CONTAINER_IMAGE}" >/dev/null
printf "\nContainer starting: "
docker ps -l -s
trap exit_hook EXIT
printf "\nAwaiting container start...\n"
for _ in $(seq 1 1 "$MAX_TRIES")
do
sleep 1
STATUS=$(docker inspect --format='{{.State.Health.Status}}' "${CONTAINER_NAME}")
if [ "${STATUS}" = "healthy" ]; then
echo "Container healthy!"
SUCCESS=1
break;
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment