MacOS下PostgreSQL@14连接失败问题求助
MacOS下PostgreSQL@14连接失败及服务启动异常解决方法
问题描述
我在MacOS上通过Homebrew安装了postgresql@14,连接数据库时遇到一系列问题:
1. 配置文件设置
我的postgres.conf配置如下:
listen_addresses = '*' port = 5432 max_connections = 100
也尝试过将listen_addresses改为'localhost',但问题依旧。
2. 连接信息
使用的连接URI:
"postgresql://localhost:5432/db_name"
3. 连接错误提示
连接时抛出以下错误:
OperationalError sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at "localhost" (::1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections?
4. 服务启动异常
- 执行
brew services start postgresql@14时返回:Bootstrap failed: 5: Input/output error - 执行
brew services restart postgresql@14看似成功,但用brew services list查看状态时显示Status error
我是新手,急需解决方法。
解决步骤
1. 检查PostgreSQL进程状态
先确认服务是否真的在运行,执行:
ps aux | grep postgres
如果输出中没有postgres相关进程,说明服务完全未启动,需要进行初始化或修复。
2. 初始化PostgreSQL数据库(首次安装或数据目录损坏时)
Homebrew安装的postgresql@14可能未自动初始化数据库目录,执行对应命令:
- Intel芯片Mac:
/usr/local/opt/postgresql@14/bin/initdb /usr/local/var/postgresql@14
- Apple Silicon芯片Mac:
/opt/homebrew/opt/postgresql@14/bin/initdb /opt/homebrew/var/postgresql@14
3. 修复brew services启动异常
Bootstrap failed通常是plist配置文件问题,执行以下命令重置服务:
brew services stop postgresql@14 brew services uninstall postgresql@14 brew services install postgresql@14 brew services start postgresql@14
4. 手动启动PostgreSQL(绕开brew services)
如果brew services仍无法正常启动,直接用pg_ctl命令启动:
# Intel芯片Mac pg_ctl -D /usr/local/var/postgresql@14 start # Apple Silicon芯片Mac pg_ctl -D /opt/homebrew/var/postgresql@14 start
启动后用以下命令确认状态:
# Intel芯片Mac pg_ctl -D /usr/local/var/postgresql@14 status # Apple Silicon芯片Mac pg_ctl -D /opt/homebrew/var/postgresql@14 status
5. 验证本地基础连接
服务启动后,先用psql命令直接测试连接,排除SQLAlchemy的配置问题:
psql -h localhost -p 5432 -d db_name
如果提示database "db_name" does not exist,先创建数据库:
createdb db_name
6. 检查防火墙设置
MacOS防火墙可能阻止了5432端口,进入「系统设置」-「网络」-「防火墙」,确认PostgreSQL被允许接收传入连接,或临时关闭防火墙测试连接是否正常。
内容的提问来源于stack exchange,提问作者codingsunflower
相关产品推荐
相关产品推荐

