Ubuntu 22.04下修改PostgreSQL默认目录及启动新数据库方法
在Ubuntu 22.04中修改PostgreSQL服务指向新数据库目录的方法
因为Ubuntu通过apt安装的PostgreSQL是用pg_ctlcluster工具管理集群的,直接修改服务文件容易出错,按以下步骤操作即可让服务指向新目录:
停止PostgreSQL服务
- 执行命令暂停当前服务:
sudo systemctl stop postgresql - 可通过以下命令确认服务已停止:
sudo systemctl status postgresql
- 执行命令暂停当前服务:
处理现有集群并创建新集群
- 若默认的14/main集群不再需要,先删除它:
sudo pg_dropcluster 14 main - 基于你已用
initdb创建的/database/new_location目录,创建新的PostgreSQL集群:sudo pg_createcluster -d /database/new_location 14 main - 确保新目录权限正确(postgres用户需拥有读写权限),若权限不足执行:
sudo chown -R postgres:postgres /database/new_location
- 若默认的14/main集群不再需要,先删除它:
启动新集群并设置自启
- 启动新创建的集群:
sudo pg_ctlcluster 14 main start - 设置集群开机自动启动:
sudo systemctl enable postgresql@14-main
- 启动新创建的集群:
验证配置有效性
- 查看服务运行状态:
sudo systemctl status postgresql@14-main - 连接数据库确认数据目录已变更:
输出应显示sudo -u postgres psql -c "SHOW data_directory;"/database/new_location。
- 查看服务运行状态:
额外注意事项
- 若原集群有需要保留的数据,先执行
pg_dumpall -U postgres > backup.sql导出数据,再在新集群中执行psql -U postgres -f backup.sql导入。 - 若原
postgresql.conf中有自定义配置,可将内容复制到新目录下的同名文件中,避免重新配置。
内容的提问来源于stack exchange,提问作者Chapa
相关产品推荐
相关产品推荐

