PostgreSQL 远程访问与数据目录迁移

349 字
2 分钟
PostgreSQL 远程访问与数据目录迁移

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

一、配置远程访问#

1. 修改认证方式#

Warning

以下操作会降低数据库安全性。trust 认证允许本地用户免密连接为任意数据库用户,仅建议在开发/测试环境使用。生产环境应保持 peer 或使用 scram-sha-256

Terminal window
# 将 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,添加:

Warning

0.0.0.0/0 表示允许所有 IP 连接,生产环境应限制为特定 IP 段,并确保使用强密码。

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

3. 监听所有网络接口#

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

listen_addresses = '*'

4. 重启服务#

Terminal window
sudo systemctl restart postgresql
sudo systemctl enable postgresql

二、数据目录迁移#

Caution

数据目录迁移操作风险较高,权限设置不正确或拷贝不完整会导致 PostgreSQL 无法启动。操作前务必停止服务并做好备份。

Terminal window
# 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

评论区

Profile Image of the Author
顾拾柒
The world is big, you have to go and see.
公告
欢迎来到我的博客!
分类
标签
站点统计
文章
81
分类
7
标签
158
总字数
83,114
运行时长
0
最后活动
0 天前
站点信息
构建平台
Vercel
博客版本
Firefly v6.12.1
文章许可
CC BY-NC-SA 4.0

文章目录