title: Can't connect to docker sql server from NET Core 2.2 Web API
body: <p>While collecting knowledge of coding .NET Core Web API in combination with docker, I came across an error that I can't solve. I already did research on the internet, but somehow none of the provided solutions worked for me.</p>
  
  <p>I have a web service called <code>Catalog.API</code> (similar to the eShopOnContainers project from Microsoft), where I have a controller called <code>CatalogController</code>.</p>
  
  <p>This is the code from the controller:</p>
  
  <pre><code>using System.Collections.Generic;
  using System.Linq;
  using System.Threading.Tasks;
  using Catalog.API.Models;
  using Microsoft.AspNetCore.Mvc;
  using Microsoft.EntityFrameworkCore;
  
  namespace Catalog.API.Controllers
  {
      [ApiController]
      [Route("api/[controller]")]
      public class CatalogController : ControllerBase
      {
          private readonly CatalogItemContext _context;
  
          public CatalogController(CatalogItemContext context)
          {
              _context = context;
          }
  
          public async Task&lt;List&lt;CatalogItem&gt;&gt; GetItemsAsync()
          {
              var items = await _context.CatalogItems.Where(model =&gt; model.Id &lt; 10).ToListAsync();
              return items;
          }
      }
  }
  </code></pre>
  
  <p>As you can see, I only have one method that should return all items from an external database, that have an id smaller than 10.</p>
  
  <p>The database is added in the <code>Startup.cs</code>:</p>
  
  <pre><code>namespace Catalog.API
  {
      public class Startup
      {
          public Startup(IConfiguration configuration)
          {
              Configuration = configuration;
          }
  
          public IConfiguration Configuration { get; }
  
          // This method gets called by the runtime. Use this method to add services to the container.
          public void ConfigureServices(IServiceCollection services)
          {
              services.AddDbContext&lt;CatalogItemContext&gt;(builder =&gt;
              {
                  builder.UseSqlServer(Configuration.GetConnectionString("Default"));
              });
  
          services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
          }
  
          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
          public void Configure(IApplicationBuilder app, IHostingEnvironment env)
          {
              if (env.IsDevelopment())
              {
                  app.UseDeveloperExceptionPage();
              }
              else
              {
                  // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                  app.UseHsts();
              }
  
              app.UseHttpsRedirection();
              app.UseMvc();
          }
      }
  }
  </code></pre>
  
  <p>The <code>appsettings.json</code> looks like this:</p>
  
  <pre><code>{
    "Logging": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "AllowedHosts": "*",
    "ConnectionStrings": {
      "Default": "Server=localhost,1433;Initial Catalog=Test.Services.CatalogDb;User Id=sa;Password=Pass@word" 
    }
  }
  </code></pre>
  
  <p>To build this web service, I created a docker file that is called from the <code>docker-compose.yml</code>:</p>
  
  <pre><code>FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 AS base
  WORKDIR /app
  EXPOSE 80
  
  FROM mcr.microsoft.com/dotnet/core/sdk:2.2 AS build
  WORKDIR /src
  
  COPY src/Services/Catalog/Catalog.API/Catalog.API.csproj /src/csproj-files/
  
  WORKDIR ./csproj-files
  RUN dotnet restore
  
  WORKDIR /src
  
  COPY . .
  WORKDIR /src/src/Services/Catalog/Catalog.API/
  RUN dotnet publish -c Release -o /app
  
  FROM build AS publish
  
  FROM base as final
  WORKDIR /app
  COPY --from=publish /app .
  ENTRYPOINT ["dotnet", "Catalog.API.dll"]
  </code></pre>
  
  <p>The <code>docker-compose.yml</code> looks like this:</p>
  
  <pre><code>version: '3.4'
  
  services:
  
    sqldata:
      ports:
        - 1433:1433
      image: mcr.microsoft.com/mssql/server:2017-latest-ubuntu
      environment:
        - ACCEPT_EULA=Y
        - SA_PASSWORD=Pass@word
  
    catalog.api:
      ports:
        - 80:80
      build:
        context: .
        dockerfile: src/Services/Catalog/Catalog.API/Dockerfile
      depends_on:
        - sqldata
  </code></pre>
  
  <p>As already mentioned, in addition to the Catalog.API web service, I am also running a SQL Server database inside a docker container. For development purposes, I am connecting to this SQL Server from DataGrip using localhost or my machine ip as the host address (<code>localhost</code> or <code>192.168.2.101</code>). Both ways work fine and I can establish a connection inside DataGrip without a problem.</p>
  
  <p>My problem is that I can not connect to SQL Server from inside the docker container in my <code>CatalogController</code>, running on localhost:80. Normally, when I call <code>localhost:80/api/catalog</code>, I should get all items out of the database (see the controller at the beginning), but somehow, I get this error:</p>
  
  <blockquote>
    <p>fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]<br>
    An error occurred using the connection to database 'Test.Services.CatalogDb' on server 'localhost,1433'.<br>
    System.Data.SqlClient.SqlException (0x80131904): 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) </p>
    
    <p>at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken)<br>
    at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)<br>
    at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)<br>
    at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)<br>
    at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)<br>
    at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal&amp; connection)<br>
    at System.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()<br>
    --- End of stack trace from previous location where exception was thrown ---</p>
    
    <p>at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnectionAsync(Boolean errorsExpected, CancellationToken cancellationToken)
        ClientConnectionId:00000000-0000-0000-0000-000000000000</p>
  </blockquote>
  
  <p>I already tried to use serveral ips (localhost, my machine ip + the ip out of docker inspect), but none is working.</p>
  
  <pre><code>Server=192.168.2.101,1433;Initial Catalog=Test.Services.CatalogDb;User Id=sa;Password=Pass@word
  </code></pre>
  
  <p>I am open for every help, that can solve my problem.
  Thanks in advance.</p>