環(huán)境
- centos 7.2
- postgresql 9.6
過程
在服務(wù)器上安裝了postgresql后铺纽,確認(rèn)5432端口成功被監(jiān)聽哟忍,卻無論如何都連不上數(shù)據(jù)庫狡门,在這里浪費(fèi)了超過2小時的時間,最后才解決了問題锅很,正確的過程整理如下:
1.在centos終端中輸入以下代碼其馏,以postgres
用戶登陸終端
root:# su - postgres
(因為postgres的管理器會以當(dāng)前用戶名為user名稱進(jìn)行登陸,由于默認(rèn)postgres沒有root名稱的user爆安,所以會報錯)
2.創(chuàng)建名稱為dbuser
的新用戶
-bash-4.2$ createuser -s dbuser
-s
的意思是以superuser
的身份創(chuàng)建用戶dbuser
3.使用剛才新建的用戶來創(chuàng)建數(shù)據(jù)庫mydb
$ createdb -O dbuser mydb
4.對 dbuser
用戶加上密碼
以 dbuser
的身份登錄 postgresql
psql -U dbuser -d mydb
其中 -U
的意思是以用戶某某來登錄叛复, -d
的意思是鏈接 mydb
這個數(shù)據(jù)庫
登錄成功后,終端符號會變成 mydb=#
扔仓,我們輸入
mydb=# \password
連續(xù)輸入兩次密碼即可
網(wǎng)上的大多數(shù)文章只能幫你到這了褐奥,但是你會發(fā)現(xiàn),根本連不上postgres翘簇,不管是本機(jī)撬码,還是網(wǎng)絡(luò)中的其他機(jī)器,在花費(fèi)了不少時間后呜笑,我發(fā)現(xiàn)了第5步
5.修改postgres的配置文件
默認(rèn)安全策略下postgres是禁止機(jī)器訪問的,需要修改
# vim /var/lib/pgsql/9.6/data/pg_hba.conf
在這個文件的末尾處,修改如下
# "local" is for Unix domain socket connections only
local all all trust
# IPv4 local connections:
host all all 127.0.0.1/32 trust
# IPv6 local connections:
host all all ::1/128 trust
修改了配置后,需要重啟 postgresql
服務(wù)张足,然后就可以很順暢地鏈接了
6.通過遠(yuǎn)程地址訪問postgresql
如果你想要通過非本機(jī)來訪問pg岩馍,那么還需要修改postgresql.conf
疫铜,我的路徑為
# vim /var/lib/pgsql/9.6/data/postgresql.conf
將`listen addresses = 'localhost' 這一行(原文被注釋了)修改為
# etc...
listen addresses = '*'
# etc...
這樣的話顽馋,數(shù)據(jù)庫變?yōu)楸O(jiān)聽任何發(fā)往本機(jī)指定端口的信息了
小貼士
全局搜索
如果你沒有 pg_hba.conf
這個目錄,可以通過
find / -name "pg_hba.conf"
來搜索這個文件
重啟 postgresql 服務(wù)的方法
- 通過命令來重啟
systemctl reload postgresql-9.6.service
- 通過 postgresql 命令重啟
/usr/pgsql-9.6/bin/pg_ctl reload
關(guān)閉iptables
如果你的服務(wù)器在更高層面上有安全組之類的設(shè)置,那么基本上就可以關(guān)掉iptables了
1.關(guān)閉iptables
systemctl stop firewalld.service
2.禁止開機(jī)啟動
systemctl disable firewalld.service
感謝以下文章給予的幫助
PostgreSQL新手入門(阮一峰)
Getting authentication failed error with postgresql from command line