【问题标题】:Connect to Postgres as SystemD service from docker-compose从 docker-compose 连接到 Postgres 作为 SystemD 服务
【发布时间】:2022-02-03 22:49:06
【问题描述】:

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

docker-compose containers ---> postgres as systemd

这是关于使用localhost 上的外部 Postgres 数据库设置 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

docker-compose YAML 文件中的 AFAIU 我需要使用 host.docker.internal 功能,以便 Docker 服务使 docker 容器从 Docker 网络中找到出路,并使用 SystemD 服务找到 localhost,例如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 服务?

【问题讨论】:

    标签: postgresql docker docker-compose systemd docker-networking


    【解决方案1】:

    原来我只需要在 YAML 代码中使用 network_mode: host 来定义 Docker 容器(容器是 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 端口,在 Airflow 网络服务器的 docker-compose YAML 服务定义中,我指定了端口:

    command: webserver -p 9999
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 2018-09-03
      相关资源
      最近更新 更多