I am trying to connect to my Postgres database using Npgsql in a .NET 5 Console App. The Postgres database is running in a Docker container. I've been connecting to the database using Azure Data Studio for a while now with no issues, so I'm a little unsure what I'm doing wrong connecting from this application.
When calling NpgsqlConnection.Open(), a System.Timeout exception is thrown.
An unhandled exception of type 'Npgsql.NpgsqlException' occurred in System.Private.CoreLib.dll: 'Exception while connecting' Inner exceptions found, see $exception in variables window for more details. Innermost exception System.TimeoutException : Timeout during connection attempt at Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
I've confirmed that the Docker container running my Postgres database is running and I can successfully connect and query it from Azure Data Studio and PGAdmin.
Here is the code in my console app. I've redacted the values in the connection string and have checked those values many, many times to make sure they are the same values I am using to connect in Azure Data Studio and PGAdmin. I've tried including the specific database name in the connection string as well, but the result was the same System.Timeout exception.
I am using Npgsql version 5.0.4.
using Dapper;
using Npgsql;
namespace EplStats
{
class Program
{
static void Main(string[] args)
{
var connStr = "Host={host};Port=5433;Username={usr};Password={pwd};";
using (var conn = new NpgsqlConnection(connStr))
{
conn.Open();
var test = conn.Query("select * from epl.teams;");
}
}
}
}
Here is my docker-compose.yml for Postgres and PGAdmin
version: "3.9"
services:
postgres-db:
image: postgres:13
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
ports:
- "5433:5432"
networks:
- pg_network
volumes:
- db_data:/var/lib/postgresql/data
pgadmin4:
image: dpage/pgadmin4
environment:
PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL}
PGADMIN_DEFAULT_PASSWORD: ${POSTGRES_PASSWORD}
ports:
- "8088:80"
networks:
- pg_network
networks:
pg_network:
driver: bridge
volumes:
db_data:
I have a feeling I am missing something obvious here since the code is relatively straight forward to open a connection from the console application.