LoginSignup
0
1

More than 1 year has passed since last update.

DockerコンテナからホストOSのPostgresにアクセス全開設定にせずにログインする方法

Last updated at Posted at 2021-06-29

概要

Prometheusで、postgres-exporterのDockerコンテナからホストOS上のpostgresにログインしたかった。

コンテナからアクセスするとlocalhostからのアクセスにならないので接続拒否される。しかし、Postgresの接続許可設定をallにはしたくない。

そこで、コンテナのIPアドレスを固定し、postgresのpg_hba.confに接続許可設定をすることで通信を可能にした。

関連記事

docker-compose.yaml

postgres-exporterコンテナからホストOSのpostgresにパスワードログインさせる。

Docker networkを作り、各コンテナにipv4_addressを割り当てるころでIPアドレスを固定。
postgres-exporterコンテナで host.docker.internal:host-gateway を渡し、コンテナからlocalhostへのアクセスを可能にする。

exporter_proxyコンテナは今回は関係ないが、他のコンテナのIPアドレスも固定する例として記載した。

詳しく知りたい方はこちらを参照。
[目次] Prometheusで監視システムを作る with Docker

docker-compose.yaml
version: '3'
services:
  # ホストOSのpostgresに接続するコンテナ
  postgres-exporter:
    container_name: quay.io/prometheuscommunity/postgres-exporter
    image: postgres-exporter
    hostname: postgres-exporter
    # ホストOSのlocalhostへ接続するための設定
    extra_hosts:
      - "host.docker.internal:host-gateway"
    # postgresへの接続情報(後述)
    env_file:
      - ./postgres-exporter/.env
    ports:
      - 127.0.0.1:9187:9187
    restart: always
    # IPアドレスの固定化
    networks:
      sample-network:
        ipv4_address: 192.168.200.2

  exporter_proxy:
    image: rrreeeyyy/exporter_proxy
    container_name: exporter_proxy
    volumes:
      - ./exporter_proxy/config:/config
    ports:
      - 9099:9099
    entrypoint: ['/exporter_proxy', '-config', '/config/config.yaml']
    restart: always
    networks:
      sample-network:
        ipv4_address: 192.168.200.3

# ネットワークを作成し、必要なIPアドレスの数だけサブネットを切る。
networks:
  sample-network:
    ipam:
      driver: default
      config:
        # 16個
        - subnet: 192.168.200.0/28

./postgres-exporter/.envの設定

postgres-exporterコンテナに設定した host.docker.internal がlocalhostの意味になるので、ホスト名はこれにする。

.env
DATA_SOURCE_NAME=postgresql://postgres_exporter:password@host.docker.internal:5432/postgres?sslmode=disable

pg_hba.conf

ホストOSのpg_hba.confに以下を追記する。
192.168.200.2(postgres_exporterコンテナ)から、postgres_exporterユーザーが、postgresデータベースに接続する設定。

# TYPE  DATABASE        USER          ADDRESS               METHOD
host    postgres   postgres_exporter      192.168.200.2/32       md5

postgresの再起動をして反映させる。これでアクセス可能となる。

参考

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