docker - 带有 Docker 的 Airflow 连接到本地主机 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 吗?
解决方案
当您尝试localhost
在 Airflow 中访问时,它会尝试连接到在 Airflow 容器上运行的 Postgres,但该容器不存在。localhost
默认情况下,来自容器的不路由到 Docker 主机。
几个选项:
host.docker.internal
使用而不是连接到 Docker 主机localhost
- 在 Docker Compose 网络中运行 Airflow 和 Postgres 并通过容器名称(
psql
等)连接
主机文件等还有其他一些方法,但以上可能是您最简单的选择。