Skip to content
VDS · 数据库

PostgreSQL:安装与您的第一个数据库

在 VDS 上安装 PostgreSQL、角色与第一个数据库、pg_hba.conf 中的认证如何工作,以及排查连接错误。

更新于 2026年8月23日

PostgreSQL 是 Python、Node.js 和 Go 应用的默认选择。它比 MySQL 更严格地对待数据,并且能更好地处理复杂查询。

安装

apt update && apt install -y postgresql postgresql-contrib   # Debian, Ubuntu
systemctl enable --now postgresql

在 AlmaLinux 和 CentOS Stream 上,您需要手动创建集群:

dnf install -y postgresql-server postgresql-contrib
postgresql-setup --initdb
systemctl enable --now postgresql

检查版本和状态:

sudo -u postgres psql -c "SELECT version();"

角色与数据库

在 PostgreSQL 中,用户被称为角色。为每个项目创建单独的角色:

sudo -u postgres psql
CREATE ROLE shop WITH LOGIN PASSWORD 'long-random-password';
CREATE DATABASE shop OWNER shop ENCODING 'UTF8';
REVOKE ALL ON DATABASE shop FROM PUBLIC;

应用程序的连接字符串:

postgresql://shop:password@127.0.0.1:5432/shop

以系统用户身份检查:

psql "postgresql://shop:password@127.0.0.1:5432/shop" -c "\dt"

身份验证

有两个文件决定谁可以从哪里登录。

/etc/postgresql/17/main/postgresql.conf:

listen_addresses = 'localhost'
port = 5432

/etc/postgresql/17/main/pg_hba.conf — 规则自上而下读取,第一条匹配的规则生效:

local   all   postgres            peer
local   all   all                 scram-sha-256
host    all   all   127.0.0.1/32  scram-sha-256

peer 方法表示“系统用户与角色匹配”——这就是为什么 sudo -u postgres psql 无需密码即可运行,而其他用户执行同样的命令则不行。

修改后执行:systemctl reload postgresql。切勿使用 trust 方法——它允许任何人无需密码直接进入。

如需外部访问,请阅读远程访问:您不能在未按地址限制的情况下将端口对外开放。

常见错误

现象原因
role "..." does not exist您正以没有对应角色的系统用户身份连接
password authentication failedpg_hba.conf 中的规则要求使用其他方法,或者未设置密码
could not connect to server: No such file or directory服务未运行,或者使用了其他端口
permission denied for schema public在 15+ 版本中,您必须显式授予 public 上的权限:GRANT ALL ON SCHEMA public TO shop;
FATAL: sorry, too many clientsmax_connections 已耗尽——请在应用侧设置连接池

日志:/var/log/postgresql/ 或 journalctl -u postgresql。

后续步骤

不要给应用程序授予超级用户角色。常规的数据库所有者角色可以完成它所需的一切,但如果迁移出错,它无法删除相邻的数据库。