在不设置Docker容器访问宿主操作系统中的Postgres数据库的完全开放权限的情况下,登录的方法
总结
我想从Prometheus的postgres-exporter Docker容器登录到主机操作系统上的postgres。
只要從容器中訪問,就無法從本地主機訪問,這樣將被拒絕連接。然而,我們不想將Postgres的連接權限設置為全部允許。
因此,我們通過將容器的IP地址設置為固定值,並在postgres的pg_hba.conf文件中進行連接許可設置,實現了通信的可能性。
以下是与这个主题相关的文章。
-
- [目次] Prometheusで監視システムを作る with Docker
- [Prometheus] Postgres Exporter with Docker
docker-compose.yaml 文件
使Postgres导出器容器登录到主机操作系统的Postgres时需要密码。
创建Docker网络,并为每个容器分配固定的IPv4地址。
通过将 host.docker.internal:host-gateway 作为参数传递给postgres-exporter容器,使容器可以访问localhost。
这次与出口代理容器无关,但是我们以其他容器的IP地址也固定为例进行记录。
如果您想了解更多详细信息,请参考这里。
[目录] 使用Docker在Prometheus中创建监控系统
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文件.
将设置为 “host.docker.internal” 的 postgres-exporter 容器意味着它将指向本地主机,因此将其作为主机名。
DATA_SOURCE_NAME=postgresql://postgres_exporter:password@host.docker.internal:5432/postgres?sslmode=disable
pg_hba.conf 只需要一种选择来进行汉语本地化改写。
在主机操作系统的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
重启PostgreSQL以使更改生效。这样就可以访问了。
可以参考
- [Docker / Docker Compose] コンテナのIPアドレスを固定する方法