Odd behavior restarting sonarqube container using crontab. Can not connect to database

Hi,

We’re trying to restart docker every night, so have written a script to perform this. It works fine if you run it from the command line, and it appears to work fine if you run it from cron. However, when run from cron after 20 seconds or so it fails to connect to the database. The error message is :-

2018.01.09 14:55:23 INFO  web[o.sonar.db.Database] Create JDBC data source for jdbc:mysql://sonarq5digital.xxx.eu-west-1.rds.amazonaws.com:3306/sonarq5digital?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&maxAllowedPacket=1073741824
2018.01.09 14:55:28 ERROR web[o.a.c.c.C.[.[.[/]] Exception sending context initialized event to listener instance of class org.sonar.server.platform.PlatformServletContextListener
java.lang.IllegalStateException: Can not connect to database. Please check connectivity and settings (see the properties prefixed by 'sonar.jdbc.').

I’m confused as to why this would work OK when the restart is performed directly, but not using cron. Here’s the script also :-

#  Function of this script:
#  - Restart Docker. (If the service is not running, the restart will effectively start Docker).
#  - Load the Sonarqube docker compose .tar file
#  - Bring up the Sonarqube container.

export TMPDIR=/var/docker-compose/tmp
HOMEDIR=$HOME/restartsonarqube

cd $HOMEDIR

# Script output will be logged to this file
log_file="$HOMEDIR/restartdocker.log"

# Name of image to load
docker_image="$HOMEDIR/aviva_sonarqube-5.4.tar"

# Start logging
echo "$(date)" | tee -a $log_file
echo "$(date) Logging to file $log_file" | tee -a $log_file

echo "$(date) Running as user $(whoami)" | tee -a $log_file
echo "$(date)" | tee -a $log_file

echo "$(date) Taking down the existing Sonarqube container" | tee -a $log_file
docker-compose -f $HOMEDIR/docker-compose-standalone.yml -p aviva down -v 2>&1 | tee -a $log_file
echo "$(date) Existing SQ taken down." | tee -a $log_file

echo "$(date) Restarting Docker service" | tee -a $log_file
sudo systemctl restart docker.service | tee -a $log_file
#sudo systemctl restart docker.service 2>&1 | tee -a $log_file
echo "$(date) Docker service restarted." | tee -a $log_file

echo "$(date) Loading Docker image: $docker_image" | tee -a $log_file
docker load -i $docker_image | tee -a $log_file

echo "$(date) Docker compose up" | tee -a $log_file
#docker-compose -f $HOMEDIR/docker-compose-standalone.yml -p aviva up -d 2>&1 | tee -a $log_file
docker-compose -f $HOMEDIR/docker-compose-standalone.yml -p aviva up -d | tee -a $log_file
echo "$(date) Image is up" | tee -a $log_file
echo "$(date) End of restart log for this run" | tee -a $log_file

# Spaces to separate runs in the log file
echo " " >> $log_file
echo " " >> $log_file