在当今的数据驱动世界中,PostgreSQL 是一款功能强大、开源且高度可扩展的关系型数据库系统。如果你正在使用 RockyLinux(RHEL 的社区替代版本),那么本文将为你提供一份详尽的 PostgreSQL 安装与配置教程,即使是 Linux 新手也能轻松上手。

一、准备工作:更新系统并安装必要工具
首先,确保你的 RockyLinux 系统是最新的,并安装一些基础工具:
RockyLinux 默认仓库中的 PostgreSQL 版本可能较旧。为了安装最新稳定版(例如 PostgreSQL 15),建议使用官方 PostgreSQL 全球开发组(PGDG)提供的 Yum 仓库。 以 PostgreSQL 15 为例,执行以下命令添加仓库: 注意:上述命令适用于 RockyLinux 9。如果你使用的是 RockyLinux 8,请将 URL 中的 现在可以安装 PostgreSQL 服务器和客户端了: 首次安装后,需要初始化数据库目录: 然后启动 PostgreSQL 服务,并设置开机自启: PostgreSQL 安装后会自动创建一个名为 切换到 postgres 用户并进入数据库命令行: 在 psql 提示符下,设置密码(将 默认情况下,PostgreSQL 只监听本地回环地址(127.0.0.1)。若需允许其他机器连接,需修改两个配置文件。 1. 修改 postgresql.conf 找到 2. 修改 pg_hba.conf 编辑客户端认证配置文件: 在文件末尾添加一行,允许特定网段(如 192.168.1.0/24)使用密码认证连接: 保存后,重启 PostgreSQL 使配置生效: 你可以通过以下命令本地连接测试: 输入你设置的密码,如果看到类似 通过本教程,你已经完成了 RockyLinux数据库部署 中最关键的一步——PostgreSQL 的安装与基础配置。无论你是开发人员、系统管理员还是学习者,掌握 Linux下PostgreSQL安装 技能都将为你的项目打下坚实的数据基础。 记住定期备份数据、更新系统,并遵循安全最佳实践。祝你在使用 PostgreSQL 的旅程中顺利高效!sudo dnf update -ysudo dnf install -y wget vim二、添加官方 PostgreSQL Yum 仓库
sudo dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-9-x86_64/pgdg-redhat-repo-latest.noarch.rpm# 禁用 RockyLinux 自带的 postgresql 模块(避免冲突)sudo dnf -qy module disable postgresql
EL-9
替换为 EL-8
。三、安装 PostgreSQL 15
sudo dnf install -y postgresql15-server postgresql15四、初始化数据库并启动服务
sudo /usr/pgsql-15/bin/postgresql-15-setup initdbsudo systemctl start postgresql-15sudo systemctl enable postgresql-15五、配置 PostgreSQL 用户与密码
postgres
的系统用户和数据库超级用户。我们需要为其设置密码以便远程或本地连接。sudo -u postgres psqlyour_password
替换为你自己的强密码):ALTER USER postgres PASSWORD 'your_password';\q六、配置远程访问(可选)
sudo vim /var/lib/pgsql/15/data/postgresql.conf#listen_addresses = 'localhost'
这一行,取消注释并改为:listen_addresses = '*'sudo vim /var/lib/pgsql/15/data/pg_hba.confhost all all 192.168.1.0/24 md5sudo systemctl restart postgresql-15七、验证安装是否成功
psql -U postgres -h localhost -Wpostgres=#
的提示符,说明 RockyLinux PostgreSQL安装 成功!八、常用命令速查
查看服务状态:systemctl status postgresql-15 停止服务:sudo systemctl stop postgresql-15 重新加载配置(不重启):sudo systemctl reload postgresql-15 查看 PostgreSQL 版本:psql -U postgres -c "SELECT version();"总结
