ホストOSから VirtualBox の中の PostgreSQL にアクセスする方法


ホストOS から VirtualBox の中の PostgreSQL にアクセスする方法です。 PostgreSQL の設定変更になりますので、 ホストOS は Windows でも MAC でも OK です。

環境

ホストOS に VirtualBox をインストールして、 その中で Ubuntu を動かしていました。

ホスト

Windows, Mac 両方の環境で検証しました。

  • Windows 10
  • macOS High Sierra 10.13.3

ゲスト

  • Ubuntu 17.10
  • PostgreSQL 9.5

ゲストOSはNAT接続にしており、ポートフォワーディングを行っていました。 NAT接続をしている方は、 ゲストOSの PostgreSQL の5432ポートにつながるように設定をしておきましょう

ポートフォワーディング設定例

設定変更

ホストOS から ゲストOS の PostgreSQL に接続できるようにするためには、 PostgreSQL の設定を変更する必要があります。

Listen Addresses の変更

/etc/postgresql/9.5/main/postresql.conf の中に、 listen_addresses の記述があります。 デフォルトではコメントアウトされています。 その記述を '*' に変更します。

PostgreSQL は Listen Addresses で記述されたクライアントからの接続を待ち受けます。 デフォルトではローカルホストからの接続のみを受け付けるようになっていて、カンマ区切りで複数のホストを指定することもできます。 PostgreSQL のドキュメントには次のように記述されています。

Specifies the TCP/IP address(es) on which the server is to listen for connections from client applications. The value takes the form of a comma-separated list of host names and/or numeric IP addresses. The special entry * corresponds to all available IP interfaces. The entry 0.0.0.0 allows listening for all IPv4 addresses and :: allows listening for all IPv6 addresses. If the list is empty, the server does not listen on any IP interface at all, in which case only Unix-domain sockets can be used to connect to it. The default value is localhost, which allows only local TCP/IP “loopback” connections to be made. While client authentication (Chapter 20) allows fine-grained control over who can access the server, listen_addresses controls which interfaces accept connection attempts, which can help prevent repeated malicious connection requests on insecure network interfaces. This parameter can only be set at server start.

Authentication Configuration の変更

/etc/postgresql/9.5/main/pg_hba.conf の中で、 DBに接続可能なホストの認証情報が記述されています。 IPv4 のところに次の行を追加します。