2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Postgresqlで他サーバのDBへアクセス

Last updated at Posted at 2014-12-13

1. はじめに

SSDサーバを建てたので,データ量が多いデータをそちらに移し,
データベース専用のサーバにしようと考え,他サーバからのアクセスの仕方をまとめます.
ついでにRailsの設定もまとめておきます.

2. Postgresの設定

postgresはデフォルトではローカルのアクセスしか許可していないため,
外部からの接続も許可するように変更します.

/etc/postgresql/9.3/main/postgresql.conf
# - Connection Settings -

# listen_addresses = 'localhost'^ ^ # what IP address(es) to listen on;
listen_addresses = '*'^ ^ # what IP address(es) to listen on;

続いて,接続を許可する種類について設定を行っていきます.

/etc/postgresql/9.3/main/pg_hba.conf
# Database administrative login by Unix domain socket
local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust
# この行を追加
host    all             all             *.*.*.*/32              trust
# IPv6 local connections:
host    all             all             ::1/128                 trust

今回は単一のサーバから許可できれば良いので良くパスも不要であり,
データベースも全てのアクセスを許可しています.

各列の設定項目はこのような形になっています.

接続方式 データベース ユーザ IP メソッド
local all all 指定IP md5
host 指定DB 指定ユーザ trust
hostssl peer
hostnoss reject
password

3. 接続確認

require 'pg'
conn = PGconn.connect('IP',PORT, '', '', 'DB', 'USER', '')

ex. Railsの場合

app/modelの中に直接rubyファイルを作成します.

app/model/foo.rb
class Foo < ActiveRecord::Base
  establish_connection(
    adapter:  'postgresql',
    host:     'IP',
    database: 'DB',
    username: 'USER',
    password: ''
  )
end
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?