我准备了一个docker-compose文件来部署带有数据库的容器:
services:
tmp-db:
image: microsoft/mssql-server-linux:latest
environment:
ACCEPT_EULA: Y
SA_PASSWORD: yourStrong(!)Password
ports:
- 1433:1433
没关系。但现在我需要创建一个数据库并构建其结构。我需要执行一些sql命令。
要检查我是否能够执行此操作,我已将command
添加到服务中:
services:
tmp-db:
image: microsoft/mssql-server-linux:latest
environment:
ACCEPT_EULA: Y
SA_PASSWORD: yourStrong(!)Password
command: /opt/mssql-tools/bin/sqlcmd -U sa -P yourStrong(!)Password -Q "SELECT [name] FROM sys.databases"
ports:
- 1433:1433
但是我遇到了以下错误:
tmp-db_1 | Sqlcmd: Error: Microsoft ODBC Driver 13 for SQL Server : Login timeout expired.
tmp-db_1 | Sqlcmd: Error: Microsoft ODBC Driver 13 for SQL Server : TCP Provider: Error code 0x2749.
tmp-db_1 | Sqlcmd: Error: Microsoft ODBC Driver 13 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..
我觉得该命令是在Sql Server实例启动之前执行的。我该如何解决?如何在启动Sql Server后执行某些sql?
答案 0 :(得分:2)
问题是在容器中只执行一个命令。在docker-compose.yml
中指定命令时,它会覆盖默认命令,该命令应该启动容器。所以你有两个选择
手动运行命令
services:
tmp-db:
image: microsoft/mssql-server-linux:latest
environment:
ACCEPT_EULA: Y
SA_PASSWORD: yourStrong(!)Password
ports:
- 1433:1433
然后你可以执行
docker-compose exec tmp-db /opt/mssql-tools/bin/sqlcmd -U sa -P yourStrong(!)Password -Q "SELECT [name] FROM sys.databases"
有两项服务 - 一项服务器和服务器;一个用于数据加载
services:
load-db:
image: microsoft/mssql-server-linux:latest
command: sh -c 'sleep 10 && /opt/mssql-tools/bin/sqlcmd -U sa -P yourStrong(!)Password -Q "SELECT [name] FROM sys.databases"'
network_mode: service:tmp-db
tmp-db:
image: microsoft/mssql-server-linux:latest
environment:
ACCEPT_EULA: Y
SA_PASSWORD: yourStrong(!)Password
ports:
- 1433:1433
在这种方法中,我们使用加载数据的命令启动另一个容器,我们在数据库服务器容器的网络上运行它。这样做只是为了避免数据库的主机名,如果您愿意,也可以将主机名也作为tmp-db
传递并删除network_mode: service:tmp-db
。