Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check that a SQL Server linux database is up and running?

I have a Docker-based application that is running against a SQL Server Linux database docker container. In the startup of the application container I want to check if the database is up and available before starting up the application. What is the correct way either using sqlcmd or other methodology, to tell that the SQL Server database is up and running?

I'm looking for something equivalent to the mysqladmin ping functionality which checks for mysql database availability.

like image 577
jhrabi Avatar asked Sep 16 '25 07:09

jhrabi


1 Answers

I had a similar use-case, and ended up using writing my own script using sqlcmd.

#!/bin/bash

for i in {1..20};
do
    # Check if Database already exists
    RESULT=`sqlcmd -S <db-address> -U <username> -P <password> -Q "IF DB_ID('DatabaseName') IS NOT NULL print 'YES'"`
    CODE=$?
    
    if [[ $RESULT == "YES" ]]
    then
        echo "Do Something."
        break
    
    elif [[ $CODE -eq 0 ]] && [[ $RESULT == "" ]]
    then
        echo "If this comes up, the database doesn't exist"
        break
        
    # If the code is different than 0, an error occured. (most likely database wasn't online) Retry.
    else
        echo "Database not ready yet..."
        sleep 1
    fi
done

$CODE equals a 0, when the command ran successfully. If the database is down, it will probably takes a couple of seconds until the command timeouts, and then you'll get a $CODE which is not zero.

like image 190
emilanov Avatar answered Sep 19 '25 01:09

emilanov