psycopg2连接本地PostgreSQL 5432端口报Connection refused错误
PostgreSQL本地连接被拒绝问题排查
报错信息
运行Python代码读取PostGIS空间数据时抛出连接错误:
Python connection to server at "localhost" (::1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connect?
报错指向本地IPv6回环地址(::1)的5432端口连接被拒绝,核心原因是客户端无法和目标端口建立TCP连接。
本次运行的原始代码如下:
import psycopg2 import geopandas as gpd with psycopg2.connect(database="osm_data_science_db",user="postgres", password='password',host='localhost') as connection: gdf = gpd.GeoDataFrama.from_postgis("""SELECT*FROM osm_amenities_areas""", connection, geom_col='geom') gdf[['osm_id','state','geom','post']].head()
排查解决步骤
按优先级从高到低依次检查:
- 检查PostgreSQL服务运行状态
5432是PostgreSQL默认端口,连接被拒绝最常见的原因是数据库服务未启动:- Windows系统:打开「服务」面板,找到名称带PostgreSQL的服务,确认状态为「正在运行」,未启动则右键选择启动
- macOS(Homebrew安装):终端执行
brew services list查看postgresql服务状态,未启动则执行brew services start postgresql - Debian/Ubuntu系Linux:终端执行
sudo systemctl status postgresql查看状态,未启动则执行sudo systemctl start postgresql,需要开机自启可追加执行sudo systemctl enable postgresql
- 修复IPv6解析不兼容问题
当前报错是客户端尝试连接IPv6地址::1失败,如果你的PostgreSQL服务默认只监听IPv4回环地址,直接把连接参数里的host='localhost'改成host='127.0.0.1',强制客户端走IPv4连接即可绕过该问题。 - 校验端口监听配置
服务启动后仍报错的话,执行端口监听检查:- Linux/macOS终端执行
netstat -an | grep 5432 - Windows命令行执行
netstat -an | findstr 5432
如果返回结果里没有127.0.0.1:5432或::1:5432的LISTEN状态记录,找到PostgreSQL安装目录下的postgresql.conf配置文件,修改listen_addresses参数值为'localhost',保存后重启PostgreSQL服务。
如果端口监听正常但后续出现认证类报错,再检查同目录下的pg_hba.conf文件,确认本地连接规则允许postgres用户通过密码认证登录。
- Linux/macOS终端执行
- 修复代码笔误
原始代码存在拼写错误:gpd.GeoDataFrama类名少写了末尾的e,连接问题解决后需要改成gpd.GeoDataFrame,否则会触发属性不存在的报错。
修正后可运行代码
import psycopg2 import geopandas as gpd # 若IPv6连接异常可将host改为'127.0.0.1' with psycopg2.connect(database="osm_data_science_db", user="postgres", password='password', host='localhost') as connection: gdf = gpd.GeoDataFrame.from_postgis("""SELECT * FROM osm_amenities_areas""", connection, geom_col='geom') print(gdf[['osm_id','state','geom','post']].head())
内容的提问来源于stack exchange,提问作者Chao
相关产品推荐
相关产品推荐

