温馨提示×

Debian怎么连接PostgreSQL

小樊
45
2026-08-28 15:30:09
栏目: 云计算

Debian 上连接 PostgreSQL,通常分为 系统层面应用层面 两种情况。下面我从常见场景一步一步说明。


一、在 Debian 上安装 PostgreSQL(如未安装)

sudo apt update
sudo apt install postgresql postgresql-client

安装完成后,PostgreSQL 会自动启动。

查看状态:

sudo systemctl status postgresql

二、使用命令行连接 PostgreSQL(本地)

1️⃣ 切换到 postgres 用户

sudo -i -u postgres

2️⃣ 使用 psql 连接

psql

或指定数据库:

psql -d postgres

✅ 成功后会看到类似提示符:

postgres=#

三、使用密码方式连接 PostgreSQL

1️⃣ 给 postgres 用户设置密码

sudo -u postgres psql
ALTER USER postgres PASSWORD 'your_password';

退出:

\q

2️⃣ 修改 pg_hba.conf 允许密码登录

编辑配置文件:

sudo nano /etc/postgresql/15/main/pg_hba.conf

版本号(如 15)用 ls /etc/postgresql/ 查看

找到类似以下内容:

local   all   all   peer

改为:

local   all   all   md5

或远程连接:

host    all   all   0.0.0.0/0   md5

重启 PostgreSQL:

sudo systemctl restart postgresql

3️⃣ 使用密码连接

psql -h localhost -U postgres -d postgres

四、远程连接 PostgreSQL(如从另一台机器)

1️⃣ 修改 postgresql.conf

sudo nano /etc/postgresql/15/main/postgresql.conf

修改:

listen_addresses = '*'

2️⃣ 修改 pg_hba.conf

添加:

host all all 0.0.0.0/0 md5

3️⃣ 重启服务

sudo systemctl restart postgresql

4️⃣ 防火墙放行 5432 端口

sudo ufw allow 5432/tcp

五、从应用程序连接 PostgreSQL

示例(Python)

import psycopg2

conn = psycopg2.connect(
    host="localhost",
    database="postgres",
    user="postgres",
    password="your_password"
)

六、常用 psql 命令

功能 命令
列出数据库 \l
切换数据库 \c dbname
列出表 \dt
退出 \q

七、常见问题

❌ peer authentication failed

  • 原因:使用系统用户登录
  • 解决:切换为 postgres 用户或改为 md5

❌ could not connect to server

sudo systemctl start postgresql

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

  • ✅ 本地还是远程?
  • ✅ 使用的是哪种语言(Python / Java / PHP / Go)?
  • ✅ Debian 版本(11 / 12)?

我可以给你更精确的配置示例。

0