1. 程式人生 > >CentOS7安裝並配置PostgreSQL

CentOS7安裝並配置PostgreSQL

步驟摘要

yum install -y https://download.postgresql.org/pub/repos/yum/9.6/redhat/rhel-7-x86_64/pgdg-centos96-9.6-3.noarch.rpm
yum install -y postgresql96-server postgresql96-contrib
/usr/pgsql-9.6/bin/postgresql96-setup initdb
systemctl start postgresql-9.6
systemctl enable postgresql-9.6
firewall-cmd --add-service=postgresql --permanent
firewall-cmd --reload
su - postgres
psql -U postgres
ALTER USER postgres with encrypted password 'abc123';
\q
exit
vi /var/lib/pgsql/9.6/data/postgresql.conf
vi /var/lib/pgsql/9.6/data/pg_hba.conf
systemctl restart postgresql-9.6.service

步驟詳情

安裝yum源

本文撰寫時,PostgreSQL 10還是測試版,因此在此演示9.6版。 
右鍵複製連結地址。 
這裡寫圖片描述

不放心是否複製成功的話可以粘貼出來看看。 
這裡寫圖片描述

以root模式進入CentOS7,輸入yum install後面加上剛剛複製的連結,回車。 
這裡寫圖片描述

輸入y,回車。 
這裡寫圖片描述

安裝PostgreSQL

輸入yum install -y postgresql96-server postgresql96-contrib並回車。 
(如果使用其他版本的PostgreSQL則需要把其中的兩個96換成對應的數字) 
這裡寫圖片描述

輸入/usr/pgsql-9.6/bin/postgresql96-setup initdb

並回車,初始化資料庫。 
(如果使用其他版本的PostgreSQL則需要把其中的9.696換成對應的數字) 
這裡寫圖片描述

輸入systemctl start postgresql-9.6並回車,啟動服務。 
輸入systemctl enable postgresql-9.6並回車,設為開機自啟。 
(如果使用其他版本的PostgreSQL則需要把其中的兩個9.6換成對應的版本) 
這裡寫圖片描述

(如果未安裝firewalld防火牆可跳過下面兩步) 
輸入firewall-cmd --add-service=postgresql --permanent並回車,開放防火牆。 
輸入firewall-cmd --reload

並回車,重啟防火牆。

修改預設PostgreSQL使用者密碼

PostgreSQL安裝後會建立一個使用者,名為postgres。 
輸入su - postgres並回車,切換至使用者。 
輸入psql -U postgres並回車,登入資料庫。 
輸入ALTER USER postgres with encrypted password 'abc123';(不要漏了“;”)並回車,設定預設使用者postgre的密碼,此處密碼為abc123,可自行修改。 
輸入\q並回車, 退出資料庫。 
輸入exit並回車,退出使用者。 
這裡寫圖片描述

配置遠端訪問

輸入vi /var/lib/pgsql/9.6/data/postgresql.conf並回車。 
(如果使用其他版本的PostgreSQL則需要把其中的9.6換成對應的版本) 
游標下翻,找到listen_addresses。 
這裡寫圖片描述

按i鍵進入插入編輯模式,如果想對所有IP開放,則將localhost改為*即可,如果想僅對部分IP開放,多個IP之間用,(逗號+空格)隔開。 
改完之後去掉“listen_address”前面的# 
這裡寫圖片描述

編輯完成後,按Esc鍵,輸入:wq並回車。 
輸入vi /var/lib/pgsql/9.6/data/pg_hba.conf並回車,將游標移至底部。 
(如果使用其他版本的PostgreSQL則需要把其中的9.6換成對應的版本) 
這裡寫圖片描述

按i鍵進入插入編輯模式,在IPv4 local connections下方新增允許連線的IP。 
如果想允許所有IPv4地址,則加入一行host all all 0.0.0.0/0 md5。IPv6方法類似。 
這裡寫圖片描述

編輯完成後,按Esc鍵,輸入:wq並回車。 
輸入systemctl restart postgresql-9.6.service並回車,重啟服務。 
(如果使用其他版本的PostgreSQL則需要把其中的9.6換成對應的版本)