在GitLab CI的Docker镜像中使用sqlcmd连接SQL Server失败
问题描述
我尝试构建一条可测试数据库变更的CI流水线,但在SQL Server环节遇到问题。定义的作业如下:
variables: MSSQL_SA_PASSWORD: <YourStrong@Passw0rd> ACCEPT_EULA: Y build_database: stage: build image: mcr.microsoft.com/mssql/server:2017-latest script: - cd './Database/Up' - /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "$MSSQL_SA_PASSWORD" -Q "SELECT @@VERSION" - for file in *.sql; do echo "sqlcmd -i $file"; /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "$MSSQL_SA_PASSWORD" -i $file; done;
SQL脚本存放在./Database/Up目录下,但作业卡在SELECT @@VERSION步骤失败,错误输出如下:
$ /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "$MSSQL_SA_PASSWORD" -Q "SELECT @@VERSION" Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : Login timeout expired. Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : TCP Provider: Error code 0x2749. Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online..
根据官方文档,应该可以通过/opt/mssql-tools18/bin/sqlcmd -S localhost -U SA -P '<YourPassword>'连接服务器,且密码已通过GitLab CI变量配置。
问题原因与解决办法
- SQL Server服务未就绪:使用
mcr.microsoft.com/mssql/server:2017-latest镜像时,容器启动后SQL Server需要时间完成初始化,直接执行sqlcmd会因服务未启动导致连接超时。 - 工具路径版本不匹配:官方文档提到的
/opt/mssql-tools18/bin/sqlcmd是新版工具路径,2017版本镜像默认安装的是旧版mssql-tools,路径为/opt/mssql-tools/bin/sqlcmd,若要使用新版需额外安装。
修改后的作业脚本(基础版)
variables: MSSQL_SA_PASSWORD: <YourStrong@Passw0rd> ACCEPT_EULA: Y build_database: stage: build image: mcr.microsoft.com/mssql/server:2017-latest script: # 循环等待SQL Server服务启动就绪 - | until /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "$MSSQL_SA_PASSWORD" -Q "SELECT 1" > /dev/null 2>&1; do echo "等待SQL Server启动..." sleep 5 done - cd './Database/Up' - /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "$MSSQL_SA_PASSWORD" -Q "SELECT @@VERSION" - for file in *.sql; do echo "执行脚本: $file"; /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "$MSSQL_SA_PASSWORD" -i $file; done;
使用新版mssql-tools18的脚本(可选)
如果需要使用官方文档中的新版工具,可在脚本中先安装:
variables: MSSQL_SA_PASSWORD: <YourStrong@Passw0rd> ACCEPT_EULA: Y build_database: stage: build image: mcr.microsoft.com/mssql/server:2017-latest script: # 安装mssql-tools18 - apt-get update && apt-get install -y mssql-tools18 # 等待服务启动,添加-C参数跳过证书验证 - | until /opt/mssql-tools18/bin/sqlcmd -S localhost -U SA -P "$MSSQL_SA_PASSWORD" -C -Q "SELECT 1" > /dev/null 2>&1; do echo "等待SQL Server启动..." sleep 5 done - cd './Database/Up' - /opt/mssql-tools18/bin/sqlcmd -S localhost -U SA -P "$MSSQL_SA_PASSWORD" -C -Q "SELECT @@VERSION" - for file in *.sql; do echo "执行脚本: $file"; /opt/mssql-tools18/bin/sqlcmd -S localhost -U SA -P "$MSSQL_SA_PASSWORD" -C -i $file; done;
内容的提问来源于stack exchange,提问作者csuvikv
相关产品推荐
相关产品推荐

