Skip to content

Instantly share code, notes, and snippets.

@toenobu
Last active December 19, 2021 02:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save toenobu/5026188d73b69046248c8792962a7b22 to your computer and use it in GitHub Desktop.
Save toenobu/5026188d73b69046248c8792962a7b22 to your computer and use it in GitHub Desktop.
Dockerコンテナのアプリからhost側にあるPostgresqlに接続したい

めっちゃはまったので、メモです。

  • 前提 premise
    • Appliction on Docker
      • デフォルトのbridgeで接続
    • Postgresql 9.5 on Mac
      • HomeBrew で インストールしたもの

Postgresql 9.5 の 設定

デフォルトの設定のままだとlocalhost以外から接続できないので、設定する。

pg_hba.confについて 88行目のとおりに、どこからもで接続できるようにする。

 85 # IPv4 local connections:
 86 #host    all             all             127.0.0.1/32            trust
 87 #host    all             all             192.168.10.0/24          trust
 88 host    all             all             0.0.0.0/0               trust

postgresql.confについて こちらも同様に、どこからもで接続できるようにする。

 59 listen_addresses = '*'      # what IP address(es) to listen on;
 60                     # comma-separated list of addresses;
 61                     # defaults to 'localhost'; use '*' for all
 62                     # (change requires restart)

起動時の Docker の設定

host側で、local addressを調べる。
$ ifconfig | grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" | grep -v 127.0.0.1 | awk '{ print $2 }' | cut -f2 -d: | head -n1
192.168.0.1

add-hostオプションを使うと、dockerの/etc/hostsにそのIPが書き込まれる $ docker run -it --rm -v $(pwd):/go/src/Application/api --add-host=docker:192.168.0.1 Docker-Image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment