下载目录:PostgreSQL: File Browser,我使用的PostgreSQLv17.5 。Linux系统:CentOS Linux release 7.9.2009 (Core)
-
安装依赖包和工具链(必须且重要!)
shellyum groupinstall "Development Tools" -y yum install -y readline-devel zlib-devel libicu-devel openssl-devel pam-devel libxml2-devel libxslt-devel systemd-devel
-
上传安装包至服务器后解压此包
shell# 先在Windows的CMD 或 macOS的terminal下执行scp命令 scp postgresql-17.5.tar.gz root@192.168.31.199:/root # Linux执行以下命令 tar -xvf postgresql-17.5.tar.gz # 解压
-
编译并安装
shellcd postgresql-17.5 ./configure \ --prefix=/opt/pgsql \ # 申明安装在哪里 --with-openssl \ --with-libxml \ --with-icu \ --with-systemd make -j $(nproc) && sudo make install # $(nproc)使用CPU多核编译
-
增加
postgres
组和postgres
用户shellgroupadd postgres && useradd -g postgres postgres passwd postgres # 定义postgres用户密码
-
创建目录并授权:创建存储数据的文件夹(我创建在**/opt/pgsql/data**)
shellmkdir -p /opt/pgsql/data && chown -R postgres:postgres /opt/pgsql
-
初始化数据库
shell# 切换至postgres用户 su -- postgres # 进入pgsql的bin目录 cd /opt/pgsql/bin # 初始化数据库 ./initdb -D /opt/pgsql/data --locale=en_US.UTF-8 --encoding=UTF8
-
修改配置文件
-
/opt/pgsql/data/postgresql.conf 新增内容如下
texlisten_addresses = '*' # 允许所有IP连接,默认是仅允许本地连接,此项必须改 port = 5432 # 默认端口,此项可忽略不增
-
/opt/pgsql/data/ pg_hba.conf 修改内容如下
tex# IPv4 local connections: # host all all 127.0.0.1/32 trust # 注释掉原来的 host all all 0.0.0.0/0 scram-sha-256 # 新增此行,允许所有IP通过密码连接 # IPv6 local connections: # host all all ::1/128 trust # 注释掉原来的 host all all ::1/128 scram-sha-256 # 新增此行,允许所有IP通过密码连接
-
-
新建/etc/systemd/system/postgresql.service服务文件,需用到root用户,请切换到root用户
shellsu - root touch /etc/systemd/system/postgresql.service
文件内容如下
tex[Unit] Description=PostgreSQL database server After=network.target [Service] User=postgres Group=postgres Type=notify User=postgres ExecStart=/opt/pgsql/bin/postgres -D /opt/pgsql/data ExecReload=/bin/kill -HUP $MAINPID [Install] WantedBy=multi-user.target
修改完成后执行
shellchown postgres:postgres /etc/systemd/system/postgresql.service systemctl daemon-reload systemctl start postgresql systemctl enable postgresql # 不希望pgsql每次开机自启,请勿执行此行命令
-
修改postgresql数据超级用户------postgres的密码,并将postgres用户添加到路径,请先将Linux切换到postgres用户
shellsu - postgres . /opt/pgsql/bin/psql -c "alter user postgres with password '自定义密码';" # 添加路径 echo 'export PATH=$PATH:/opt/pgsql/bin' >> ~/.bash_profile echo 'export PGDATA=/opt/pgsql/data' >> ~/.bash_profile source ~/.bash_profile
-
开启防火墙端口(请先将Linux切换到root用户)
shellsu - root firewall-cmd --add-port=5432/tcp --permanent # 开放端口且永久生效 firewall-cmd --reload # 重载配置
若远程连接不上,那么请重启服务,用postgres用户或root都行
systemctl restart postgresql