title: How do you connect to SQL Server running on the host from a .NET app in a windows docker container
body: <p>I have a Windows docker container and a simple test app that is attempting to connect with the SQL Server running on the host, but it is unable to connect.</p>
  
  <p>I am able to ping the host from the container using "ping -4 hostmachinename", but the SqlConnection Open method fails.</p>
  
  <p>To test I run these commands:</p>
  
  <p>docker build --tag=heydocker .
  docker run heydocker:latest</p>
  
  <pre><code># Dockerfile:
  FROM microsoft/dotnet-framework
  WORKDIR /app
  COPY . /app
  EXPOSE 1433
  CMD ["program.exe"]
  </code></pre>
  
  <p>This is my app code:</p>
  
  <pre><code>// program.cs:
  using System;
  using System.Data;
  using System.Data.Common;
  using System.Data.SqlClient;
  
  namespace Test
  {
      public static class program
      {
         const string CONNECT = "Data Source=docker.for.win.localhost;Database=MG108RC3_All;User ID=sa;Pwd=password;Network Library=dbmssocn";
  
          public static void Main()
          {
              Console.WriteLine( "Hello Docker" );
  
              try
              {
                  using ( var con = new SqlConnection( CONNECT ) )
                  {
                      con.Open();
                      Console.WriteLine( "Open SUCCESS" );
                  }
              }
              catch ( Exception ex )
              {
                  Console.WriteLine( $"ERROR: {ex.Message}" );
              }
          }
      }
  }
  </code></pre>
  
  <p>I have tried omitting the EXPOSE in the Dockerfile, as well as using EXPOSE 1433:1433.</p>
  
  <p>I have also tried using the actual machine name in the connection string, as well as host.docker.internal.</p>
  
  <p>When using docker.for.win.localhost I get the exception: ERROR: 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: 0 - No such host is known.)</p>
  
  <p>When using the machine name I get: ERROR: 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: 0 - The wait operation timed out.)</p>
  
  <p>I have tried various options for --net, but since I am able to ping my host with the default network settings I am not confident that is the problem.</p>