下載目錄:PostgreSQL: File Browser,我使用的PostgreSQLv17.5。Linux系統:CentOS Linux release 7.9.2009 (Core)
-
安裝依賴包和工具鏈(必須且重要!)
yum groupinstall "Development Tools" -y yum install -y readline-devel zlib-devel libicu-devel openssl-devel pam-devel libxml2-devel libxslt-devel systemd-devel
-
上傳安裝包至服務器后解壓此包
# 先在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 # 解壓
-
編譯并安裝
cd 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
用戶groupadd postgres && useradd -g postgres postgres passwd postgres # 定義postgres用戶密碼
-
創建目錄并授權:創建存儲數據的文件夾(我創建在**/opt/pgsql/data**)
mkdir -p /opt/pgsql/data && chown -R postgres:postgres /opt/pgsql
-
初始化數據庫
# 切換至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 新增內容如下
listen_addresses = '*' # 允許所有IP連接,默認是僅允許本地連接,此項必須改 port = 5432 # 默認端口,此項可忽略不增
-
/opt/pgsql/data/ pg_hba.conf 修改內容如下
# 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用戶
su - root touch /etc/systemd/system/postgresql.service
文件內容如下
[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
修改完成后執行
chown postgres:postgres /etc/systemd/system/postgresql.service systemctl daemon-reload systemctl start postgresql systemctl enable postgresql # 不希望pgsql每次開機自啟,請勿執行此行命令
-
修改postgresql數據超級用戶——postgres的密碼,并將postgres用戶添加到路徑,請先將Linux切換到postgres用戶
su - 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用戶)
su - root firewall-cmd --add-port=5432/tcp --permanent # 開放端口且永久生效 firewall-cmd --reload # 重載配置
若遠程連接不上,則重啟服務,用postgres用戶或root都行
systemctl restart postgresql