Search code examples
c#postgresqlsshconnectionremote-connection

How to create a connection from .NET Service to Remote PostgreSQL server


I am not able to connect to the remote PostgreSQL server from C# .NET Code using some connection string. (My connection string contain basic information like host address, port, username, password, database name).

I am able to connect to the PostgreSQL server from PGAdmin 4 using SSH Tunnel, I have Remote login (username & password), port (22) and Private RSA key.

My connection string: Server=HOST_ADDRESS;Port=HOST_PORT;User Id=POSTGRES_USERNAME;Password=POSTGRES_PASSWORD;Database=POSTGRES_DATABASE_NAME;

Note: I am using Npgsql .NET Assembly

And the error I am getting is:

No connection could be made because the target machine actively refused it
 Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.NpgsqlConnector.<RawOpen>d__153.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Npgsql.NpgsqlConnector.<Open>d__149.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Npgsql.ConnectorPool.<AllocateLong>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Npgsql.NpgsqlConnection.<>c__DisplayClass32_0.<<Open>g__OpenLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Npgsql.NpgsqlConnection.Open()

Solution

  • Check your pg_hba.conf file in your data directory. This indicates who can and cannot connect to your database. The default configuration is quite restrictive (errs on the side of caution methinks).

    If you trust all machines within your network, provided they have a userid/password (think work environment with a firewall), you can add something like this to the file:

    host     all     all     0.0.0.0/0       md5
    

    If not, check the docs or even the file itself does a good job of explaining the various options.