简体   繁体   English

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

[英]Apache Airflow can't connect to localhost database

I am using Airflow and Postgres on Docker.我在 Docker 上使用 Airflow 和 Postgres。 I have the following connection where I do a DML command (outside Airflow):我有以下连接,我在其中执行 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()

I am using Docker and the Postgres' container is available on localhost:5433.我正在使用 Docker,并且 Postgres 的容器在 localhost:5433 上可用。 I can perfectly use Pgadmin and do DML commands from Python.我可以完美地使用 Pgadmin 并从 Python 执行 DML 命令。

I instantiated the Postgress ( db ojbect) class and created the following task in a DAG:我实例化了 Postgress ( db ojbect) 类并在 DAG 中创建了以下任务:

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

However, when I open the Airflow UI this messages pops up and I can't run the DAG:但是,当我打开 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?

I am using this Dockerfile for Airflow.我将这个Dockerfile 用于 Airflow。 I also tried in the "connections" section in the Airflow UI, but I got the same message.我还尝试了 Airflow UI 的“连接”部分,但我得到了相同的消息。 I know for sure that the connection is up and running.我确定连接已启动并正在运行。

The hostname of postgres is "postgres" not "localhost". postgres 的主机名是“postgres”而不是“localhost”。

this name is defined by the name of the postgres service in the docker-compose.此名称由 docker-compose 中的 postgres 服务的名称定义。

services:
  postgres:
    image: postgres:13

also, you can see the connection string in the docker-compose (in bold)此外,您可以在 docker-compose 中看到连接字符串(粗体)

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

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

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