在 CentOS 7 上安装 PostgreSQL 的步骤如下:
首先需要配置 PostgreSQL 的官方 YUM 源:
sudo yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
例如安装 PostgreSQL 14(当前稳定版本):
sudo yum install -y postgresql14-server
如果需要其他版本(如 13/15),将命令中的14替换为对应版本号。
sudo /usr/pgsql-14/bin/postgresql-14-setup initdb
sudo systemctl start postgresql-14
sudo systemctl enable postgresql-14
编辑配置文件:
sudo vi /var/lib/pgsql/14/data/postgresql.conf
将listen_addresses修改为:
编辑访问控制文件:
sudo vi /var/lib/pgsql/14/data/pg_hba.conf
在文件末尾添加允许远程访问的规则:
host all all 0.0.0.0/0 md5
重启服务使配置生效:
sudo systemctl restart postgresql-14
切换到 postgres 用户:
设置 postgres 用户密码:
ALTER USER postgres WITH PASSWORD 'your_password';
创建新用户和数据库:
CREATE USER your_username WITH PASSWORD 'your_password';
CREATE DATABASE your_database OWNER your_username;
GRANT ALL PRIVILEGES ON DATABASE your_database TO your_username;
sudo firewall-cmd --permanent --add-port=5432/tcp
sudo firewall-cmd --reload
psql -U postgres -d postgres -h localhost -p 5432