gpt4 book ai didi

python - Apache Airflow 无法连接到本地主机数据库

转载 作者:行者123 更新时间:2023-12-05 05:38:18 31 4
gpt4 key购买 nike

我在 Docker 上使用 Airflow 和 Postgres。我在执行 DML 命令时有以下连接(在 Airflow 之外):

 # Constructor method initializing the connection to DB and creating cursor
def __init__(self, db="projeto-pos", user="postgres", host="localhost", password=my_psswd, port="5433"):
self.conn = psycopg2.connect(
database=db, host=host, port=port, password=password, user=user)
self.cur = self.conn.cursor()

我正在使用 Docker 并且 Postgres 的容器在 localhost:5433 上可用。我可以完美地使用 Pgadmin 并从 Python 执行 DML 命令。

我实例化了 Postgress (db ojbect) 类并在 DAG 中创建了以下任务:

insert_into = PythonOperator(
task_id='insert_into',
python_callable=db.insert_into
)

但是,当我打开 Airflow UI 时会弹出此消息,我无法运行 DAG:

Broken DAG: [/opt/airflow/dags/projeto_api.py] Traceback (most recent call last):
File "/opt/airflow/dags/functions/db_manipulation.py", line 10, in __init__
database=db, host=host, port=port, password=password, user=user)
File "/home/airflow/.local/lib/python3.7/site-packages/psycopg2/__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: connection to server at "localhost" (127.0.0.1), port 5433 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (::1), port 5433 failed: Cannot assign requested address
Is the server running on that host and accepting TCP/IP connections?

我正在使用 this用于 Airflow 的 Dockerfile。我也在 Airflow UI 的“连接”部分尝试过,但我收到了相同的消息。我确定连接已启动并正在运行。

最佳答案

postgres 的主机名是“postgres”而不是“localhost”。

此名称由 docker-compose 中的 postgres 服务名称定义。

services:
postgres:
image: postgres:13

此外,您还可以在 docker-compose 中看到连接字符串(粗体)

AIRFLOW__DATABASE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow@postgres/airflow

关于python - Apache Airflow 无法连接到本地主机数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72959915/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com