You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.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服务:

  1. Host:填写OVH VPS的公网IP地址(即你Putty SSH连接时用的地址)
  2. Port:填写PostgreSQL在VPS上的监听端口,默认是5432(若修改过postgresql.conf的port参数则填对应值)
  3. 必备验证步骤:
    • 重启PostgreSQL服务使配置生效:sudo systemctl restart postgresql
    • 检查OVH后台防火墙和VPS系统防火墙(如ufw),确保5432端口对外开放
    • 在应用所在机器测试端口连通性:nc -zv <VPS公网IP> 5432(或telnet <VPS公网IP> 5432),确认能正常连通

场景2:应用通过SSH隧道连接(与PgAdmin同方式)

如果依赖Putty的SSH隧道访问,连接字符串需对应本地隧道映射:

  1. Host:填写localhost(因为隧道在本地机器监听端口)
  2. Port:填写隧道的本地端口5434
  3. 注意:必须保持Putty的SSH隧道处于已连接状态,应用才能通过隧道访问远程数据库

额外排查点

  • 确认VPS上PostgreSQL服务正常运行:sudo systemctl status postgresql
  • 查看PostgreSQL日志(通常在/var/log/postgresql/目录),排查是否有连接拒绝的具体原因
  • 检查连接字符串拼写:确保Host/Port参数名无错误,用户名、密码、数据库名称准确
  • 临时关闭VPS防火墙测试:若关闭后能连接,说明是防火墙规则限制,需重新配置允许5432端口入站流量

内容的提问来源于stack exchange,提问作者Alchoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 04:48:20