Apache Airflow 无法连接本地数据库。

3

我正在使用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对象)类,并在DAG中创建了以下任务:
insert_into = PythonOperator(
        task_id='insert_into',
        python_callable=db.insert_into
    )

然而,当我打开Airflow用户界面时,此消息弹出,我无法运行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?

我正在使用这个 Dockerfile来运行Airflow。我也在Airflow UI的“连接”部分尝试过,但是收到了相同的消息。我确定连接已经成功运行。

1个回答

1

PostgreSQL的主机名为"postgres"而不是"localhost"。

该名称由docker-compose中PostgreSQL服务的名称定义。

services:
  postgres:
    image: postgres:13

此外,您可以在docker-compose中查看连接字符串(加粗部分)

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


你是对的!但我有另一个Dockerfile,其中我使用了Metabase和Postgres。在这个Dockerfile中,我设置了卷、网络等。我应该删除Airflow Dockerfile中的Postgres服务吗? - Luis Felipe
1
@LuisFelipe,你的airflow数据库连接已经改成docker了吗?如果是这样的话,那么你就不需要在airflow docker中定义postgres,因为你已经自己创建了一个。 - ozs
不,我还没有更改Airflow的数据库连接。你能否给我发送一份文档,让我了解如何进行更改?我是Airflow的新手。@ozs - Luis Felipe
我面临的另一个问题是,如果我在Airflow Docker中删除Postgres服务,则无法启动所有服务,因为某些服务依赖于Postgres。 - Luis Felipe
1
@LuisFelipe,在docker-compose中,你有一个名为AIRFLOW__DATABASE__SQL_ALCHEMY_CONN的环境变量。你需要根据你的新连接进行更改。请注意,在airflow中,localhost指的是airflow本身,而不是机器。如果你正在同一台机器上运行postgres,则主机名是该机器的名称。 - ozs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接