.NET Core+EF连接VPS中远程PostgreSQL数据库遇连接超时问题
OVH VPS PostgreSQL 远程连接超时问题排查与解决
异常信息
启动应用时持续抛出以下连接超时异常:
System.AggregateException: One or more errors occured. (An exception has been raised that is likely due to a transient failure.) ---> System.InvalidOperationException: An exception has been raised that is likely due to a transient failure. ---> Npgsql.NpgsqlException (0x80004005): Exception while connecting ---> System.TimeoutException: Timeout during connection attempt
已执行操作
- 修改
postgresql.conf:将listen_addresses从localhost改为* - 修改
pg_hba.conf:末尾添加规则host all all 0.0.0.0/0 md5 - 调整连接字符串格式:
Host=HOST_ADDRESS;Port=HOST_PORT;Username=myusername;Password=mypassword;Database=mydatabasename;
核心困惑
不确定连接字符串中Host和Port的正确取值,虽能通过Putty建立SSH隧道(本地5434→远程5432)用PgAdmin4连接,但应用直接使用该配置无法成功。
解决方案分两种场景处理
场景1:应用直接远程连接(无需SSH隧道)
这种方式下应用直接访问VPS的公网PostgreSQL服务:
- Host:填写OVH VPS的公网IP地址(即你Putty SSH连接时用的地址)
- Port:填写PostgreSQL在VPS上的监听端口,默认是
5432(若修改过postgresql.conf的port参数则填对应值) - 必备验证步骤:
- 重启PostgreSQL服务使配置生效:
sudo systemctl restart postgresql - 检查OVH后台防火墙和VPS系统防火墙(如ufw),确保
5432端口对外开放 - 在应用所在机器测试端口连通性:
nc -zv <VPS公网IP> 5432(或telnet <VPS公网IP> 5432),确认能正常连通
- 重启PostgreSQL服务使配置生效:
场景2:应用通过SSH隧道连接(与PgAdmin同方式)
如果依赖Putty的SSH隧道访问,连接字符串需对应本地隧道映射:
- Host:填写
localhost(因为隧道在本地机器监听端口) - Port:填写隧道的本地端口
5434 - 注意:必须保持Putty的SSH隧道处于已连接状态,应用才能通过隧道访问远程数据库
额外排查点
- 确认VPS上PostgreSQL服务正常运行:
sudo systemctl status postgresql - 查看PostgreSQL日志(通常在
/var/log/postgresql/目录),排查是否有连接拒绝的具体原因 - 检查连接字符串拼写:确保
Host/Port参数名无错误,用户名、密码、数据库名称准确 - 临时关闭VPS防火墙测试:若关闭后能连接,说明是防火墙规则限制,需重新配置允许
5432端口入站流量
内容的提问来源于stack exchange,提问作者Alchoder
相关产品推荐
相关产品推荐

