In my previous post we use a simple sleep command to wait out the sql start up and prevent our sql commands from executing too early. I wanted to see if I could write a better check for this and not have to hope my guess at a sleep time is correct.
I was able to come up with a solution using sqlcmd. The script below will attempt to make a connection to sql and set the output to a variable. Until this connection is successful, the script will keep trying every 1 second.
At the end I create a database to just verify we were in fact successful in waiting out the SQL startup.
checkstatus.sh
echo "Checking SQL Server"
STATUS=$(/opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P VeRYSECR3T! -d master -Q "SET NOCOUNT ON; SELECT 1" -W -h-1 )
while [ "$STATUS" != 1 ]
do
sleep 1s
echo "Checking SQL Server"
STATUS=$(/opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P VeRYSECR3T! -d master -Q "SET NOCOUNT ON; SELECT 1" -W -h-1 )
done
echo "SQL UP!"
/opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P VeRYSECR3T! -d master -Q "CREATE DATABASE SERVERUP" -W -h-1
You can find the complete solution in the branch below.
https://github.com/runwithliz/DockerSQLBlog1/tree/AlternateWait
