代码之家  ›  专栏  ›  技术社区  ›  ngruson

使用Powershell Core初始化SQL Server Linux容器中的数据库

  •  0
  • ngruson  · 技术社区  · 3 年前

    我正在Linux容器中运行SQL Server。当容器启动时,我希望进行一些初始化,并使用Powershell Core创建一个数据库。

    我的Dockerfile如下所示:

    FROM mcr.microsoft.com/mssql/server:2017-latest
    
    ENV ACCEPT_EULA="Y" `
      DATA_PATH="./data" `
      sa_password="MyP@ssw0rd"
    
    VOLUME ${DATA_PATH}
    WORKDIR ./init
    
    RUN apt-get update
    RUN apt-get install -y powershell
    
    COPY SomeFolder/Initialize-Database.ps1 .
    CMD pwsh ./Initialize-Database.ps1 -sa_password $env:sa_password -data_path $env:DATA_PATH -Verbose
    

    在Powershell脚本中,我将安装SQLServer模块以执行SQL查询。

    Set-PSRepository -Name PSGallery -InstallationPolicy Trusted
    Install-Module SQLServer
    
    if ($sa_password -ne "_") {
        Write-Verbose 'Changing SA login credentials'
        $sqlcmd = "CREATE DATABASE my-db"
        Invoke-SqlCmd -Query $sqlcmd -ServerInstance "."
    }
    

    这个 Invoke-SqlCmd 命令失败,出现连接错误:

    A network-related or instance-specific error occurred while
         | establishing a connection to SQL Server. The server was not
         | found or was not accessible. Verify that the instance name is
         | correct and that SQL Server is configured to allow remote
         | connections. (provider: TCP Provider, error: 40 - Could not
         | open a connection to SQL Server)
    

    如何检查SQL实例是否已启动,如果未启动,如何启动? 当我使用此映像启动容器并执行到容器中时, Get-SqlInstance -ServerInstance "." -Credential Get-Credential 失败,错误为“无法连接到服务器”。

    0 回复  |  直到 3 年前
        1
  •  0
  •   ngruson    3 年前

    找到了。在Dockerfile中,我现在在SQL启动后调用Powershell脚本:

    CMD ( /opt/mssql/bin/sqlservr & ) | grep -q "Service Broker manager has started" \
        && pwsh ./Initialize-Database.ps1 -sa_password $SA_PASSWORD -data_path $DATA_PATH -Verbose
    

    https://www.kenmuse.com/blog/devops-sql-server-dacpac-docker