繁体   English   中英

从 docker-compose 连接到 Postgres 作为 SystemD 服务

[英]Connect to Postgres as SystemD service from docker-compose

我需要从 docker-compose 文件中连接到作为 SystemD 服务运行的 Postgres 服务器实例。

docker-compose containers ---> postgres as systemd

这是关于使用localhost上的外部 Postgres DB 设置 Airflow 。

我采用了docker-compose示例:

curl -LfO 'https://airflow.apache.org/docs/apache-airflow/2.2.3/docker-compose.yaml'

但是,他们在那里定义了一个 Postgres 容器,其中 Airflow 通过解析 Docker 网络中的postgres主机连接到该容器。

但是我已经通过 SystemD 在机器上运行了 Postgres,我可以通过以下方式检查它的状态:

# make sure the service is up and running
systemctl list-units --type=service | grep postgres.*12
# check the process
ps aux | grep postgres.*12.*config_file
# check the service details
systemctl status postgresql@12-main.service

AFAIU inside the docker-compose YAML file I need to use the feature host.docker.internal so the Docker service makes the docker container find their way out of the Docker network and find localhost with the SystemD services eg Postgres.

我已经为docker-compose设置了 Airflow YAML 文件:

---
version: '3'
x-airflow-common:
  &airflow-common
  image: ${AIRFLOW_IMAGE_NAME:-apache/airflow:2.2.3}
  environment:
    &airflow-common-env
    AIRFLOW__CORE__EXECUTOR: LocalExecutor
    AIRFLOW__CORE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow@host.docker.internal/airflow
    ...
  extra_hosts:
    - "host.docker.internal:host-gateway"

那里发生了很多事情,但关键是 SQLAlchemy 连接字符串使用host.docker.internal作为主机。

现在,当我调用命令docker-compose -f airflow-local.yaml up airflow-init时,我在输出日志中看到 Airflow 抱怨它没有找到 Postgres 服务器:

airflow-init_1       | psycopg2.OperationalError: connection to server at "host.docker.internal" (172.17.0.1), port 5432 failed: Connection refused
airflow-init_1       |  Is the server running on that host and accepting TCP/IP connections?

Docker 特殊网络和 OS 网络之间的 DNS 分辨率可能存在问题,不知道如何解决此问题。

如何制作 Docker 容器以找出在localhost上提供的 SystemD 服务?

结果我只需要在 Docker 容器定义的 YAML 代码中使用network_mode: host (容器是docker-compose术语中的服务)。

通过这种方式,Docker 虚拟网络以某种方式绑定到笔记本电脑网络层(“localhost”或“127.0.0.1”)。 Docker 的人不鼓励这种设置,但有时在处理遗留系统时事情会很混乱,所以你必须解决过去所做的事情。

然后,您可以使用localhost访问作为 SystemD 服务运行的 Postgres DB。

唯一需要注意的是有人在使用network_mode: host时不能使用端口映射,否则docker-compose会报错:

"host" network_mode is incompatible with port_bindings

因此,您必须删除类似于以下内容的 YAML 部分:

ports:
  - 9999:8080

并以不同的方式整理端口(TCP 套接字)。

在我的特定场景(气流的东西)中,我做了以下事情:

对于使 Airflow 网络服务器(docker 容器/服务)到达localhost上的 Postgres DB(SystemD 服务/守护进程)的主机/网络:

# see the use of "localhost"
AIRFLOW__CORE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow@localhost/airflow

对于 TCP 端口,在docker-compose YAML 服务定义中为 ZD1662521E6B89809B85A825FCEB7B234 web 指定端口:

command: webserver -p 9999

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM