Home About Contact
PostgreSQL , Docker

Docker + PostgreSQL で -h localhost 指定を省略したい alias 設定 macOS

Postgres をホストOS上 に直接入れないで、Docker で使いたい。 しかし、Docker で動かしている Postgres に psql コマンドなどで アクセスしようとするとき -h localhost を省略することができない。

macOS を使っているので psql, pg_dump などのコマンドは Homebrew の brew install libpq で入れることができる。

brew install libpq すると最後に:

If you need to have libpq first in your PATH, run:
  echo 'export PATH="/opt/homebrew/opt/libpq/bin:$PATH"' >> /Users/moca/.bash_profile

といわれる。要するに /opt/homebrew/opt/libpq/bin にパスを通せばよい。

そこで直接パスを通す代わりに ~/.bashrc に次の alias を追加することにした。

alias psql="/opt/homebrew/opt/libpq/bin/psql -h localhost"
alias pg_dump="/opt/homebrew/opt/libpq/bin/pg_dump -h localhost"
alias pg_restore="/opt/homebrew/opt/libpq/bin/pg_restore -h localhost"

これで psql, pg_dump, pg_restore コマンドを使うとき常に -h localhost が付与されるので、 次のように あたかもホストOSに直接インストールした Postgres を使うかのように psql コマンドを使える。

$ psql -U postgres -d mydb

しばらくはこれでしのぐ。