温馨提示×

Linux 下 pgAdmin 如何连接数据库

小樊
57
2026-08-20 08:12:29
栏目: 智能运维

在 Linux 下使用 pgAdmin 连接 PostgreSQL 数据库,一般流程如下(适用于 pgAdmin 4,Web 版):


一、前提条件

1. 已安装 PostgreSQL

确认 PostgreSQL 已安装并运行:

psql --version

启动数据库服务(以 systemd 为例):

sudo systemctl start postgresql
sudo systemctl enable postgresql

检查状态:

sudo systemctl status postgresql

2. 已安装 pgAdmin 4

方式一:通过包管理器(推荐)

Ubuntu / Debian:

sudo apt update
sudo apt install pgadmin4

CentOS / Rocky / Alma:

sudo dnf install pgadmin4

方式二:Python 虚拟环境(通用)

python3 -m venv pgadmin4
source pgadmin4/bin/activate
pip install pgadmin4

启动:

pgadmin4

浏览器访问:

http://127.0.0.1:5050

二、配置 PostgreSQL 允许连接

1. 修改 pg_hba.conf

路径通常在:

/var/lib/pgsql/data/pg_hba.conf
# 或
/etc/postgresql/*/main/pg_hba.conf

添加或修改:

# 本地连接
local   all   all   md5

# 远程连接(如需要)
host    all   all   0.0.0.0/0   md5

2. 修改 postgresql.conf(如需远程)

listen_addresses = '*'

重启 PostgreSQL:

sudo systemctl restart postgresql

三、创建数据库用户(如需要)

切换到 postgres 用户:

sudo -u postgres psql

创建用户和数据库:

CREATE USER myuser WITH PASSWORD 'mypassword';
CREATE DATABASE mydb OWNER myuser;
GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;
\q

四、使用 pgAdmin 连接数据库

1. 打开 pgAdmin

浏览器访问:

http://localhost:5050

首次使用需设置 pgAdmin 登录密码


2. 添加服务器(Server)

  1. 左侧 Servers → 右键 → Create → Server
  2. General 页
    • Name:任意(如 LocalPG)
  3. Connection 页
    • Host name/address:
      • 本地:localhost 或 127.0.0.1
      • 远程:服务器 IP
    • Port:5432
    • Maintenance database:postgres
    • Username:数据库用户名
    • Password:数据库密码
    • 勾选 ✅ Save password

点击 Save


五、常见问题排查

1. 连接被拒绝

could not connect to server: Connection refused

✅ 检查:

sudo systemctl status postgresql
netstat -an | grep 5432

2. 密码认证失败

password authentication failed

✅ 检查:

  • 用户名/密码是否正确
  • pg_hba.conf 是否使用 md5

3. 远程连接失败

✅ 检查:

  • 防火墙是否放行 5432
sudo ufw allow 5432
  • PostgreSQL 是否监听公网 IP

六、总结流程

安装 PostgreSQL
启动数据库
配置 pg_hba.conf
创建用户/数据库
安装 pgAdmin4
浏览器打开 pgAdmin
添加 Server 并连接

如果你愿意,可以告诉我:

  • ✅ Linux 发行版(Ubuntu / CentOS / Arch)
  • ✅ 本地还是远程数据库
  • ✅ 报错信息

我可以给你 精确到命令级别 的解决方案。

0 踩