通过ssh使用SQL脚本失败,但不能直接在主机上启动

时间:2018-01-08 12:41:24

标签: mysql docker jenkins jenkins-pipeline

我已经配置了Jenkins Job,我的Pipeline看起来像这样:

        stage ('Preparing SQL Database'){
        steps{
            //Starting MYSQL Image
            sh '(sudo sshpass -p "PASSWORD" ssh -o StrictHostKeyChecking=no  $user@$host "sudo docker run --name nameofthecontainer -p 13306:3306 -d mysql:mysql")'

            sh '(sudo sshpass -p "PASSWORD" ssh -o StrictHostKeyChecking=no  $user@host "/opt/docker/dockerdeployment/databasescript.sh")'
        }

我的databasescript.sh看起来像这样(只导入一个SQL-DUMP):

sudo docker exec -i nameofthecontainer  /usr/bin/mysql -u $MYSQLUSER -pPassword $MYSQLOPTIONS $MYSQLDB -e "DROP DATABASE IF EXISTS ${MYSQLDB};CREATE DATABASE ${MYSQLDB} DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci; commit;"
sudo docker exec -i nameofthecontainer  /usr/bin/mysql -u $MYSQLUSER -pPassword $MYSQLOPTIONS $MYSQLDB < /srv/Dump.sql

done

当我直接在主机上执行脚本时,它会成功。 但是当我尝试运行Jenkins-Job(通过ssh执行此数据库脚本)时,会出现以下错误消息:

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 0
(...)
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

我终于解决了它。问题是,当执行第二步时,mysql容器尚未准备好接受连接。我在两个步骤之间使用sleep命令修复它。