75 字
1 分钟
PostgreSQL 远程访问与数据目录迁移
2026-01-25

尚未安装 PostgreSQL?参见 PostgreSQL 安装指南

一、配置远程访问#

1. 修改认证方式#

# 将 host 连接的认证方式从 ident 改为 md5(密码认证)
sudo sed -i '/^host/s/ident/md5/' /etc/postgresql/14/main/pg_hba.conf
# 将本地连接的认证方式从 peer 改为 trust
sudo sed -i '/^local/s/peer/trust/' /etc/postgresql/14/main/pg_hba.conf

2. 允许任意 IP 连接#

编辑 /etc/postgresql/14/main/pg_hba.conf,添加:

# 允许所有 IP 使用密码连接
host all all 0.0.0.0/0 md5

3. 监听所有网络接口#

编辑 /etc/postgresql/14/main/postgresql.conf,取消注释并修改:

listen_addresses = '*'

4. 重启服务#

sudo systemctl restart postgresql
sudo systemctl enable postgresql

二、数据目录迁移#

# 1. 停止服务
systemctl stop postgresql
# 2. 拷贝数据到新目录
cp -rf /var/lib/postgresql/14/main /opt/postgresql/
# 3. 设置权限
chown -R postgres:postgres /opt/postgresql/
chmod 700 /opt/postgresql/
# 4. 修改配置文件中的数据目录
vim /etc/postgresql/14/main/postgresql.conf
# 修改:data_directory = '/opt/postgresql/main'
# 5. 启动服务
systemctl start postgresql
# 6. 验证
psql -U postgres -c 'SHOW data_directory;'
分享

如果这篇文章对你有帮助,欢迎分享给更多人!

PostgreSQL 远程访问与数据目录迁移
https://blog.olinl.com/posts/postgresql-config/
作者
顾拾柒
发布于
2026-01-25
许可协议
CC BY-NC-SA 4.0

目录