How to connect Dockerized ASP.NET Core app ->Dockerized PostgreSQL?


I have 2 Dockers: my ASP.NET Core Web server -p 5001:80 postgresql -p 5451:5432 When I configure my Web Server to work with postgresql running on my host it works. But when I run configure myWeb App to work with postgresql in Docker , run http://localhost:5001 it

starts but then an error appears:

    warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
          Failed to determine the https port for redirect.
    fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
          An unhandled exception has occurred while executing the request.
    System.InvalidOperationException: An exception has been raised that is likely due to a transient failure.
     ---> Npgsql.NpgsqlException (0x80004005): Exception while connecting
     ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (99): Cannot assign requested address [::1]:5451

If I connect the app to an external non-dockerized PostgreSQL - it works fine.

What is incorrect and how to fix it?

There is my docker-compose file

asked on Stack Overflow Jul 28, 2020 by ZedZip • edited Jul 30, 2020 by ZedZip

1 Answer


So, localhost here refers to the locahost of the container which runs the webserver, not your localhost. Therefore you can't use localhost to refer to another container, without doing some networking-related things first.

There are several ways to proceed. Since you mention in the comment you're using docker-compose, I would advise the following:

With docker-compose, networking is relatively simple, if all the services that need to communicate with each other are included in the docker-compose.yml file, you run all of them with docker-compose up. If you haven't specified any specific network in the docker-compose file, docker-compose sets up a single network for all the included services, which makes it possible for each container to reach the other ones, by using a hostname identical to the container name.

Basically, you can then replace localhost with the service-name of the service you want, i.e. if postgres is called "db" in your docker-compose file, you replace localhost:5451 with db:5432.

If you specify custom networks in your docker-compose file, then you have to make sure the web-server and postgres are using the same network.

If you need to run the webapp with docker run instead of docker-compose up, then you need to include a --network argument so that they use the same network.

More info here

Edit: Corrected port number. We now need to use the container port, not the host port, as mentioned by @Adiii in above comment.

answered on Stack Overflow Jul 28, 2020 by Christian Fosli • edited Jul 28, 2020 by Christian Fosli

User contributions licensed under CC BY-SA 3.0