在 Debian 系统上配置 PostgreSQL 主要包括 安装、初始化、基本配置、用户与数据库管理、远程访问 等步骤。下面按常见使用场景一步步说明(以 Debian 11/12 为例,PostgreSQL 13/15 通用)。
sudo apt update
sudo apt install postgresql postgresql-client
安装完成后,PostgreSQL 会自动:
postgrespostgressudo systemctl status postgresql
启动 / 停止 / 重启:
sudo systemctl start postgresql
sudo systemctl stop postgresql
sudo systemctl restart postgresql
sudo -i -u postgres
psql
退出:
\q
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';
createdb mydb
或:
CREATE DATABASE mydb OWNER myuser;
/etc/postgresql/<版本>/main/
主要文件:
postgresql.conf → 核心配置pg_hba.conf → 客户端认证编辑 postgresql.conf:
sudo nano /etc/postgresql/15/main/postgresql.conf
修改:
listen_addresses = '*'
(默认是 localhost)
编辑:
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 -- 连接信息
sudo apt purge postgresql postgresql-client
sudo rm -rf /var/lib/postgresql/
如果你告诉我:
我可以给你一套 更精确的配置方案(包括安全加固)。