MRainzo
MRainzo

Reputation: 4010

Connecting postgres docker instance to dotnet core 3.1 gives "nodename nor servname provided, or not known error"

I have a postgres sql spun up using docker with the following docker-compose file

version: '3.8'
  services:
    db:
      image: postgres:latest
      container_name: quoters
      ports:
        - 5432:5432
      environment:
        POSTGRES_USER: ${POSTGRES_USER:-postgres}
        POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-password}
        POSTGRES_DB: quoters
      networks:
        - quoters
      volumes:
        - quoters:/data/db/quoters
        - ./database/init.sql:/docker-entrypoint-initdb.d/init.sql
      restart: always
  networks:
    quoters:
      driver: bridge

  volumes:
    quoters:

I am trying to connect to this postgres sql instance locally from my dotnet core webapi application. Below is my appsettings.json

{
  "ConnectionStrings": {
  "DefaultConnection": 
     "host=db;port=5432;database=quoters;username=postgres;password=password"
  },
  "Logging": {
    "LogLevel": {
    "Default": "Information",
    "Microsoft": "Warning",
    "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

I get the connectionString and use it in the Startup.cs file with the following line

var connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddRepository(connectionString);

The services.AddRepository(string) is an extension method I created. I then use this connectionString in an ISqlConnectionFactory implementation.

When I try to test the API on Swagger, I get the following error

System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (00000005, 0xFFFDFFFF): nodename nor servname provided, or not known
   at System.Net.Dns.InternalGetHostByName(String hostName)
   at System.Net.Dns.GetHostAddresses(String hostNameOrAddress)
   at Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.NpgsqlConnector.RawOpen(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.ConnectorPool.AllocateLong(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.<>c__DisplayClass32_0.<<Open>g__OpenLong|0>d.MoveNext()

I can't seem to place a finger on what is wrong. (I have a feeling something is off with my connectionString). Please any help on resolving this issue will be appreciated

Additional information

Upvotes: 2

Views: 3771

Answers (1)

Bleu802
Bleu802

Reputation: 31

Change your connection string to

"User ID=postgres;Password=changeme;Server=localhost;Port=5432;Database= quoters;Integrated Security=true;Pooling=true;"

Upvotes: 3

Related Questions