我准备了一个docker-compose文件来部署带有数据库的容器:
services: tmp-db: image: microsoft/mssql-server-linux:latest environment: ACCEPT_EULA: Y SA_PASSWORD: yourStrong(!)Password ports: - 1433:1433
没关系。但是现在我需要创建一个数据库并建立其结构。我需要执行一些sql命令。为了检查我是否能够做到这一点,我将其添加command到服务中:
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?
问题是在容器中仅执行一个命令。当您在docker-compose.yml其中指定命令时,它将覆盖默认命令,该默认命令应用于启动容器。所以你有两个选择
docker-compose.yml
手动运行命令
然后你可以执行
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。
tmp- db
network_mode: service:tmp-db