I am having 2 docker containers on my linux server. One container is a postgres database. The other container is a C# Web Api.
Now I want to connect to the postgres database from the web api. I have created a docker network and both of the containers are in this network. In the connection string I have the container name of the postgres database.
I am getting following error in the Web Api Logs: Unhandled exception. Npgsql.NpgsqlException (0x80004005): Failed to connect to 172.18.0.5:62451 ---> System.Net.Sockets.SocketException (111): Connection refused
I don't think it is a DNS failure because the IP Address showing in the error is correct. The port is also correct.
Does anyone have any idea why it might not work? I can provide logs if they are required for understanding the issue.
Thanks in advance!
I made the database publicly available for testing purposes and when I run the Web Api from Visual Studio it is working. (changing the host to the domain name inside the connection string) When I am connecting from pgadmin it is working too.
In the postgres container I made sure that listen_addresses is set to * because in the documentation it said that this is necessary for connecting from other containers. (listen_addresses='*') I have also checked the pg_hba.conf that the gateway is allowed: host all all 172.18.0.1/16 trust or host all all 172.18.0.1/16 md5
I have always restarted the postgres container after I made a change.
Edit:
This are my docker run commands:
docker run --name postgres-database -e POSTGRES_PASSWORD=PASSWORD --network shared-network -p 62451:5432 -d postgres -c listen_addresses=*
docker run -p 12345:80 -d --name my-api --network shared-network my-api
So I was able to get this working. In the docker run command I was specifying that the port of the database outside the container is 62451 and mapped to the inside port 5432:
docker run --name postgres-database -e POSTGRES_PASSWORD=PASSWORD --network shared-network -p 62451:5432 -d postgres -c listen_addresses=*
However in the connection string in my C# web api I still had to use port 5432. Otherwise I was getting the connection refused error.
Maybe this can help someone who is struggling with that problem.
I am still not understanding this behavior and would appreciate any explanations.