Skip to content

Instantly share code, notes, and snippets.

@knwng
Created April 4, 2019 12:48
Show Gist options
  • Save knwng/04b873b064b71a273b89d403d17aaa37 to your computer and use it in GitHub Desktop.
Save knwng/04b873b064b71a273b89d403d17aaa37 to your computer and use it in GitHub Desktop.
create mysql container and wait until it's ready for production in docker
#!/bin/sh
# create mysql container
MYSQL_USER="admin"
MYSQL_PASSWORD="passwd"
CONTAINER_NAME="mysql_container"
docker run -d -t \
--name ${CONTAINER_NAME} \
-e MYSQL_ROOT_PASSWORD=abcde \
-e MYSQL_DATABASE="exampledb" \
-e MYSQL_USER=${MYSQL_USER} \
-e MYSQL_PASSWORD=${MYSQL_PASSWORD} \
mysql:5.7 \
--network network \
--network-alias db \
--character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
# get ip address of this container
MYSQL_IP=$(docker inspect ${CONTAINER_NAME} | grep '"IPAddress"' | awk 'NR==2 {print $2}' | sed 's/"//g;s/\,//g')
# wait mysql to initialize, check status every 10 seconds
MAX_LOOP=100
START_TIME=$(date "+%s")
CHECK_INTERVAL=10
COUNTER=1
while ! mysql --protocol TCP -h ${MYSQL_IP} -u ${MYSQL_USER} -p${MYSQL_PASSWORD} -e "show databases;" > /dev/null 2>&1; do
sleep ${CHECK_INTERVAL}
COUNTER=`expr ${COUNTER} + 1`
CURR_TIME=$(date "+%s")
INTERVAL=$((CURR_TIME-START_TIME))
echo "Already wait mysql to initialize for ${INTERVAL} seconds"
if [ ${COUNTER} -gt ${MAX_LOOP} ]; then
>&2 echo "We have been waiting for MySQL too long already. Job failed"
exit 1
fi;
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment