MacOS Monterey M1芯片下psql连接PostgreSQL失败求助
问题描述
执行psql postgres时触发以下错误:
psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: Connection refused
Is the server running locally and accepting connections on that socket?
已尝试操作:
- 通过Homebrew重启PostgreSQL:
brew services restart postgresql - 卸载PostgreSQL:
brew uninstall postgresql - 安装并启动PostgreSQL 14:
brew install postgresql@14 brew services start postgresql@14 brew link postgresql@14 --force
排查与解决步骤
1. 确认PostgreSQL服务实际运行状态
先通过Homebrew查看服务状态:
brew services list
若postgresql@14显示started,再用进程命令验证:
ps aux | grep postgres
如果未找到postgres相关进程,手动启动服务:
pg_ctl -D /opt/homebrew/var/postgresql@14 start
(注:M1芯片Homebrew默认路径为/opt/homebrew,Intel芯片为/usr/local)
2. 检查套接字文件是否存在
查看报错中提到的套接字文件是否生成:
ls -la /tmp/.s.PGSQL.5432*
若文件不存在,检查PostgreSQL配置文件的套接字目录设置:
cat /opt/homebrew/var/postgresql@14/postgresql.conf | grep unix_socket_directories
确保配置值包含/tmp,若不包含,修改配置后重启服务:
# 编辑配置文件,将unix_socket_directories一行修改为: unix_socket_directories = '/tmp' # 保存后重启服务 brew services restart postgresql@14
3. 检查5432端口占用情况
确认5432端口是否被其他程序占用:
lsof -i :5432
若存在占用进程,可杀掉该进程,或修改PostgreSQL配置文件postgresql.conf中的port参数更换端口。
4. 初始化数据库(针对新安装场景)
如果是首次安装postgresql@14,可能未完成数据库初始化,执行:
initdb /opt/homebrew/var/postgresql@14 -E utf8
完成后重新启动服务:
brew services start postgresql@14
5. 配置环境变量
确保postgresql@14的bin目录加入系统PATH,M1芯片路径为/opt/homebrew/opt/postgresql@14/bin,将其添加到~/.zshrc(若使用zsh终端):
echo 'export PATH="/opt/homebrew/opt/postgresql@14/bin:$PATH"' >> ~/.zshrc source ~/.zshrc
重新打开终端后执行psql postgres尝试连接。
内容的提问来源于stack exchange,提问作者Alejandro Martinez

