温馨提示×

Debian怎么配置PostgreSQL

小樊
48
2026-08-28 15:20:11
栏目: 云计算

在 Debian 系统上配置 PostgreSQL 主要包括 安装、初始化、基本配置、用户与数据库管理、远程访问 等步骤。下面按常见使用场景一步步说明(以 Debian 11/12 为例,PostgreSQL 13/15 通用)。


一、安装 PostgreSQL

1. 更新软件源

sudo apt update

2. 安装 PostgreSQL

sudo apt install postgresql postgresql-client

安装完成后,PostgreSQL 会自动:

  • 创建一个系统用户 postgres
  • 创建一个数据库超级用户 postgres
  • 启动服务

二、检查服务状态

sudo systemctl status postgresql

启动 / 停止 / 重启:

sudo systemctl start postgresql
sudo systemctl stop postgresql
sudo systemctl restart postgresql

三、使用 PostgreSQL(本地)

1. 切换到 postgres 用户

sudo -i -u postgres

2. 进入 psql 命令行

psql

退出:

\q

四、创建用户与数据库

1. 创建新用户

createuser --interactive

示例:

Enter name of role to add: myuser
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) y
Shall the new role be allowed to create more roles? (y/n) n

或在 psql 中:

CREATE USER myuser WITH PASSWORD 'mypassword';

2. 创建数据库

createdb mydb

或:

CREATE DATABASE mydb OWNER myuser;

五、配置 PostgreSQL(常用)

1. 配置文件位置

/etc/postgresql/<版本>/main/

主要文件:

  • postgresql.conf → 核心配置
  • pg_hba.conf → 客户端认证

2. 修改监听地址(允许远程访问)

编辑 postgresql.conf

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

修改:

listen_addresses = '*'

(默认是 localhost


3. 配置客户端认证(pg_hba.conf)

编辑:

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

示例(允许密码登录):

# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
host    all             all             0.0.0.0/0               md5

常用认证方式:

  • peer:本地系统用户
  • md5:密码
  • trust:免密(不推荐生产)

修改后重启:

sudo systemctl restart postgresql

六、设置用户密码(远程登录必须)

sudo -u postgres psql
ALTER USER myuser WITH PASSWORD 'mypassword';

七、测试连接

本地

psql -U myuser -d mydb

远程(从另一台机器)

psql -h <服务器IP> -U myuser -d mydb

八、防火墙(如有)

sudo ufw allow 5432/tcp

九、常用管理命令

\l        -- 查看数据库
\dt       -- 查看表
\du       -- 查看用户
\conninfo -- 连接信息

十、卸载 PostgreSQL

sudo apt purge postgresql postgresql-client
sudo rm -rf /var/lib/postgresql/

如果你告诉我:

  • ✅ 是 本地开发 还是 服务器
  • ✅ 是否需要 远程访问
  • ✅ PostgreSQL 版本 / Debian 版本

我可以给你一套 更精确的配置方案(包括安全加固)。

0