0
5

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にSSHトンネルで接続する方法

Last updated at Posted at 2017-11-17

目的/条件

  • PostgreSQLベースのWebアプリケーション(Java,PHP,Perl etc)のDBを分離して別ホストで運用したい。
  • 接続はSSHトンネル(ポートフォワーディング)で行う
  • OS再起動時にSSHトンネルを自動的に開始したい
  • アプリケーションのソースコードは一切変更したくない
  • アプリケーションからlocalhostのポート5432にアクセスしたら別ホストのPostgreSQLにつながってほしい

条件

  • アプリケーションサーバのホスト名を app.mydomain.com とする
  • DBサーバのホスト名を db.mydomain.com とする
  • アプリケーションサーバからDBサーバにSSHで接続可能にfirewallやtcp-wrapperで設定されている
  • アプリケーションサーバではLinuxベースでsystemdでdaemon等の起動管理をしている

手順1:SSHトンネルの用意

  • アプリケーションサーバの任意のユーザ(user1@appとする)から、DBサーバの任意のユーザ(user2@dbとする)にパスワード無しでSSHログインできるようにしておく。user1@appの公開鍵をuser2@dbの./ssh/authoriezed_keysに登録すればよい
  • user1@app, user2@db 共に、アプリケーション実行やDBアクセスの権限等は不必要で、全く無関係のユーザで構わない。
  • DBサーバにPostgreSQLをインストールし、目的のアプリケーションのDBを動作させておく。

手順2:アプリケーションサーバ側のPostgreSQLの停止

  • PostgreSQLを停止するか、ポートを変更して起動運用する。

手順3:SSHトンネル接続を自動実行する設定

  • 以下のファイルをrootで作る。ファイル名のpgtunnelの部分は適宜変更してよい。
/etc/systemd/system/pgtunnel.service
[Unit]
Description = PostgreSQL ssh tunnlel to db.mydomain
After=network.target sshd.service

[Service]
ExecStart=/usr/bin/ssh -f -N -L 5432:db.mydomain:5432 user2@db.mydomain
Type=forking
User=appuser

[Install]
WantedBy = multi-user.target

  • 以下のコマンドで起動してみる。うまくいったらOS再起動して再確認する。
systemctl daemon-reload
systemctl enable pgtunnel.service
systemctl start pgtunnlen.service

以上で完了です

0
5
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
0
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?