1. 检查PostgreSQL服务状态
首先确认PostgreSQL服务是否正在运行,使用以下命令查看服务状态:
sudo systemctl status postgresql
若服务未启动,执行以下命令启动服务:
sudo systemctl start postgresql
并设置开机自启:
sudo systemctl enable postgresql
2. 配置PostgreSQL允许远程访问(若需远程连接)
默认情况下,PostgreSQL仅允许本地连接(localhost),需修改两个核心配置文件:
postgresql.conf:/etc/postgresql/<版本>/main/postgresql.conf,如/etc/postgresql/16/main/postgresql.conf),找到listen_addresses参数,将其修改为*(允许所有IP连接)或指定具体IP(如192.168.1.100):listen_addresses = '*'pg_hba.conf:/etc/postgresql/16/main/pg_hba.conf),在文件末尾添加以下行,允许所有IP通过MD5加密密码认证连接(可根据需求缩小IP范围,如192.168.1.0/24):host all all 0.0.0.0/0 md5sudo systemctl restart postgresql3. 检查防火墙设置
Ubuntu系统默认使用ufw防火墙,需允许PostgreSQL的默认端口(5432)通过:
sudo ufw status(若未启用,可执行sudo ufw enable启用);sudo ufw allow 5432/tcp4. 验证pgAdmin连接配置
在pgAdmin中创建服务器连接时,确保以下信息填写正确:
localhost或127.0.0.1;若为远程连接,填写服务器IP地址;5432(若修改过postgresql.conf中的port参数,需填写对应端口);postgres)及对应密码(可通过sudo -u postgres psql登录并执行ALTER USER postgres WITH PASSWORD '新密码';修改密码)5. 检查PostgreSQL用户权限
确保连接使用的用户具有访问目标数据库的权限:
postgres用户:sudo -i -u postgres;psql;myuser授权访问数据库mydb):GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;\q6. 查看PostgreSQL日志定位问题
若以上步骤均无法解决,可通过查看PostgreSQL日志获取详细错误信息:
日志文件通常位于/var/log/postgresql/<版本>/main/目录下(如/var/log/postgresql/16/main/postgresql.log),使用以下命令实时查看日志:
sudo tail -f /var/log/postgresql/<版本>/main/postgresql.log