在 Debian 上配置 PostgreSQL,通常包括 安装、初始化、远程访问、用户/数据库管理、性能与自启动 等步骤。下面给你一套从零到可用的完整配置流程(适用于 Debian 10/11/12,PostgreSQL 13/15 通用)。
sudo apt update
sudo apt upgrade -y
sudo apt install -y postgresql postgresql-client
安装完成后,PostgreSQL 会自动:
postgressudo systemctl status postgresql
启动 / 重启 / 停止:
sudo systemctl start postgresql
sudo systemctl restart postgresql
sudo systemctl enable postgresql
PostgreSQL 默认使用 peer 认证,需要切换到 postgres 用户操作:
sudo -i -u postgres
进入后使用:
psql
退出:
\q
exit
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 new roles? (y/n) n
或直接用 SQL:
CREATE USER myuser WITH PASSWORD 'mypassword';
createdb mydb
或:
CREATE DATABASE mydb OWNER myuser;
编辑配置文件:
sudo nano /etc/postgresql/15/main/postgresql.conf
(版本号可能是 13 / 14 / 15)
找到:
#listen_addresses = 'localhost'
改为:
listen_addresses = '*'
编辑:
sudo nano /etc/postgresql/15/main/pg_hba.conf
在末尾添加(示例):
host all all 192.168.1.0/24 md5
host all all 0.0.0.0/0 md5
host all all localhost md5
sudo systemctl restart postgresql
sudo -u postgres psql
ALTER USER myuser WITH PASSWORD 'mypassword';
sudo ufw allow 5432/tcp
⚠️ 云服务器记得 安全组放行 5432
\l -- 查看数据库
\du -- 查看用户
\dt -- 查看表
\c dbname -- 切换数据库
\q -- 退出
确认:
sudo systemctl is-enabled postgresql
postgres 用户远程登录md5 或 scram-sha-256安装 → 创建用户 → 创建数据库 → 设置密码 → 修改 pg_hba.conf → 重启
如果你需要:
可以直接告诉我你的使用场景(开发 / 生产 / 云服务器)。