Ruby on RailsのpostgreSQLデータベースにローカルネットワーク(LAN/外部)から接続するのに時間がかかったので少し紹介します。
database.yml
development:
adapter: postgresql
encoding: unicode
database: englishtool_development
pool: 5
username: englishtool
password: password1
host: 192.168.99.101
test:
adapter: postgresql
encoding: unicode
database: englishtool_test
pool: 5
username: englishtool
password: password1
host: 192.168.99.101
エラーが……
$ rake db:setup
could not connect to server: Connection refused
Is the server running on host "192.168.99.101" and accepting
TCP/IP connections on port 5432?
Couldn't create database for {"adapter"=>"postgresql", "encoding"=>"unicode", "database"=>"englishtool_development", "pool"=>5, "username"=>"englishtool", "password"=>"password1", "host"=>"192.168.99.101"}
rake aborted!
PG::ConnectionBad: could not connect to server: Connection refused
Is the server running on host "192.168.99.101" and accepting
TCP/IP connections on port 5432?
Tasks: TOP => db:setup => db:schema:load_if_ruby => db:create
解決方法
(ローカルのlocalhostでは正常に接続できる状態であることを前提しとしています。)
- postgresq.confファイルの修正
``` sudo vim /etc/postgresql/10/main/postgresql.conf # 追記 listen_addresses = '*' ```PostgreSQLは、デフォルトでは自ホストからの接続しか許可していない。
- 接続できるクライアントを設定する
-
local network
-
host all all 192.168.0.0/16 md5
- host all all 0.0.0.0/0 trust
全IP許可認証なしなのでセキュリティガバガバですが、開発環境なら問題ないでしょう。
IPの部分ですが、192.168.0.0/16でも良いかと思います。検証はしていないので確証はありません。認証の部分もmd5でいいかと思います。
<ol>
<li>restart</li>
</ol>
sudo /etc/init.d/postgresql restart
## 検証
<code>pgweb --url postgres://englishtool:[email protected]:5432/englishtool_development</code>
$ rake db:setup Database ‘englishtool_development’ already exists Database ‘englishtool_test’ already exists — enable_extension(“plpgsql”) -> 0.1347s — enable_extension(“plpgsql”) -> 1.4060s
## 参考
- [Configuring PostgreSQL to Accept Connections From Computers on Your Network | ScreenSteps Workgroup | ScreenSteps Desktop 2.9 and Workgroup Documentation](http://help.bluemangolearning.com/m/screensteps-workgroup/l/18259-Configuring-PostgreSQL-to-Accept-Connections-From-Computers-on-Your-Network)
- [Access PostgreSQL server from LAN - Stack Overflow](https://stackoverflow.com/questions/22080307/access-postgresql-server-from-lan)
- [他ホストから接続するための設定](http://rina.jpn.ph/~rance/linux/postgresql/connect.html) ← best