在學習一項新技能之前,必先利其器,也就是需要先懂得如何安裝PostgreSQL數據庫。這里記錄下在Centos7.6 安裝PostgreSQL數據庫,版本10.1的過程,以下步驟緊湊:
一、更新postgreSQL數據庫的源
可以從postgreSQL源網址下載安裝yum源,點擊https://yum.postgresql.org/repopackages.php#pg10
選擇centos7-x86 64,右鍵選擇復制鏈接,然后在系統終端執行以下命令,更新yum源:
yum install https://download.postgresql.org/pub/repos/yum/10/redhat/rhel-7-x86_64/pgdg-centos10-10-2.noarch.rpm -y
二、安裝PostgreSQL數據庫
2.1 查看postgresql源的rpm包
可以通過下面命令,在終端查看剛剛安裝的postgresql源的rpm包,然后來安裝對應版本的postgresql。
yum list | grep postgresql
執行以下命令安裝postgreSQL數據庫的server:
yum install postgresql10-contrib postgresql10-server -y
三、配置數據庫
Postgresql安裝目錄在/usr/pgsql-10,而Postgresql的數據目錄會放在/var/lib/pgsql/版本號/data目錄下
3.1 初始化數據庫
可以通過運行命令,來查看PostgreSQL 的命令幫助 :
/usr/pgsql-10/bin/postgresql-10-setup --help
可以看到,initdb參數可以用以初始化數據庫:
然后運行:
/usr/pgsql-10/bin/postgresql-10-setup initdb
可以看到以下顯示,則為安裝並初始化成功:
3.2 啟動數據庫
- 執行命令,啟動數據庫
sudo systemctl start postgresql-10
- 執行命令,設置開機自啟動
sudo systemctl enable postgresql-10.service
- 報錯解決,在啟動數據庫時,遇到錯誤如下,google了一下,在這發現原因https://github.com/PostgresApp/PostgresApp/issues/206:
這是由於可能系統中安裝過PostgreSQL數據庫,然后同樣IP下的端口被占用了,需要卸載掉之前的PostgreSQL rpm包,然后重新啟動即可。卸載命令:
yum remove postgresql
四、登陸PostgreSQL數據庫
4.1 登陸數據庫
postgresql在安裝時默認會添加用戶postgres,可以通過以下命令進入數據並設置密碼:
su - postgres #切換到postgres用戶下 psql #登陸數據庫
- 運行psql報錯如下:
- 這是由於psql命令沒有設置好環境變量,可以利用軟鏈來解決,執行命令,來源https://stackoverflow.com/questions/6790088/postgresql-bash-psql-command-not-found
ln -s /usr/pgsql-10/bin/psql /usr/bin/psql
執行完上述步驟,應該可以看到如下的畫面,則證明數據庫登陸成功:
4.2 修改默認用戶名密碼
執行以下命令:
ALTER USER postgres WITH PASSWORD <password>;
其中password是你要設置的密碼,如下所示:
五、完成
至此在Centos7上安裝postgreSQL數據庫基本實現,下面大家可以專心學習如何使用postgreSQL數據庫了,祝大家學習愉快~