I am trying to access the PostgreSQL on the server from a Docker container in which I run a .net app.
My Dockerfile contains the following environment variables:
ENV DB_DATABASE=db_name
ENV DB_USERNAME=db_username
ENV DB_PASSWORD=db_pw
ENV DB_HOST=public IP (not localhost!)
ENV DB_PORT=port (not the standard 5432)
In Startup.cs I construct the connection string like so:
string host = Environment.GetEnvironmentVariable("DB_HOST").ToString();
string port = Environment.GetEnvironmentVariable("DB_PORT").ToString();
string db_name = Environment.GetEnvironmentVariable("DB_DATABASE").ToString();
string db_username = Environment.GetEnvironmentVariable("DB_USERNAME").ToString();
string db_password = Environment.GetEnvironmentVariable("DB_PASSWORD").ToString();
string db_setting = String.Format("Host={0}; Port={1}; Username={2}; Password={3}; Database={4};",host, port, db_username, db_password, db_name);
I am sure that the port, IP, etc for the database are not wrong because they are used in other Docker containers.
The errors that I get:
System.InvalidOperationException: An exception has been raised that is likely due to a transient failure.
---> Npgsql.NpgsqlException (0x80004005): Exception while connecting
---> System.Net.Sockets.SocketException (111): Connection refused
They files the error point me are database queries.
2
Answers
The problem is solved. Apparently, the database port has changed. I find that pretty strange because I had another app that was using the same database with the old port and it was working just fine.
Try to update the following code snippet:
To