Airflow Docker 连接到本地主机 PostgreSQL

Airflow with Docker connect to a local Host PostgreSQL

我运行气流docker。

我想在我本地主机上的 PostgresSQl 中查询一些数据。

这是我在我 dag 中的连接:

def queryPostgresql():
    conn_string="dbname='datawarehouse' host='localhost' user='postgres' password='admin'"
    conn=db.connect(conn_string)
    df=pd.read_sql("select name,city from test",conn)
    df.to_csv('data.csv')
    print("-------Data Saved------")

我正在添加到气流的连接:

psycopg2.OperationalError: could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?

是否可以从我的 Airflow Docker 在我的 PgSQL 中查询?我应该在 docker 中安装 PgSQL 吗?

当您尝试访问 Airflow 中的 localhost 时,它会尝试连接到 Airflow 容器上的 Postgres 运行,而该容器并不存在。默认情况下,来自容器的 localhost 不会路由到 Docker 主机。

几个选项:

  • 使用 host.docker.internal 而不是 localhost
  • 连接到 Docker 主机
  • 运行 Docker 中的 Airflow 和 Postgres 组成网络并通过容器名称连接(psql 等)

主机文件等还有一些其他方法,但以上可能是您最简单的选择。