0

The problem I encountered here was with Host value in the connection string.

When using Host=localhost;Port=5432;... and building the application over Docker Compose from Visual Studio the connection fails with the following error:

Npgsql.NpgsqlException: 'Exception while connecting'
Inner Exception
ExtendedSocketException: Cannot assign requested address [::1]:5432

The solution to the problem is to simply use Host=host.docker.inner;Port=5432;... instead.

But what I do not get is what is actually wrong here. The database indeed runs on localhost:5432 which I confirmed by connecting to it using pgAdmin tool and this exact address as a server URL. I could access the tables, the data, etc.

So why doesn't the connection from ASP.NET Core work?

  • Which `localhost`? Your outer host system and the application container both independently believe they are `localhost` (as does PostgreSQL, if it's in a container) and those are different `localhost`s. – David Maze Nov 05 '21 at 10:55
  • And there goes the answer. :) I didn't know that the container running the WebApi thinks of himself as having own `localhost`. I thought that all `localhost`s mentioned in anything Docker-related reffers to the host machines `localhost`. – Hervis Daubeny Nov 05 '21 at 11:24
  • So the `Host=host.docker.inner` points to the result of Docker Compose "build" and the connection using this conn-string works because the `host.docker.inner` contains *(exposes)?* collection of all the ports that the containers in the corresponding Docker Compose expose? – Hervis Daubeny Nov 05 '21 at 11:29
  • `host.docker.inner` would resolve to "the host machine", what you're describing as "localhost", and it would be able to access any `ports:` that are _published_. Compose `expose:` doesn't really do anything. To connect between containers, see also [Networking in Compose](https://docs.docker.com/compose/networking/) in the Docker documentation; also [From inside of a Docker container, how do I connect to the localhost of the machine?](https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach) discussing `localhost`. – David Maze Nov 05 '21 at 11:38

0 Answers0