Docker run and sqlcmd together errors

932 Views Asked by At

Putting together a script to quickly add a SQL Server Linux instance inside a docker container, then immediately connecting to it to test. Seems like the run command and sqlcmd can't be run in the same script.

Say you run this in a .ps1 file:

  #create the container with sql server
  docker run `
  -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=Awesome1!" `
     -p 11433:1433 `
     --name shuriken --hostname shuriken --restart=always `
     -d microsoft/mssql-server-linux:2017-latest;

  #try to connect to it
  $ConnectionString = "Server=localhost,11433;Database=master;User Id=sa; Password=Awesome1!";
  $sql = 'SELECT @@SERVERNAME AS ServerName;';
  Invoke-Sqlcmd -ConnectionString $ConnectionString -Query $sql;

You get an error:

Invoke-Sqlcmd : A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)

But if after that you immediately comment out the docker run command, it works. Connects to the same SQL Server just fine:

shuriken

I've tried Invoke-SqlCmd, SqlCmd, cmdlets from the SqlServer module and placing them in another file I call here; they all give the same error.

1

There are 1 best solutions below

0
On

Adding a Start-Sleep -s 4; between docker run and Invoke-SqlCmd works. Looks like it just needed some breathing room. 4 seconds was the lowest I could go before querying.