如何使用 sqlalchemy 在 Docker 中访问 postgresql? [英] How do I access postgresql within Docker with sqlalchemy?

查看:92
本文介绍了如何使用 sqlalchemy 在 Docker 中访问 postgresql?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 SQLAlchemy 与 dockerized PostgreSQL 服务器进行交互.类似的东西:

I'm trying to interact with a dockerized PostgreSQL server using SQLAlchemy. Something like:

engine = create_engine('postgresql://user:user_password@localhost:5432/database')
df.to_sql('table', engine)

这给了我这个错误:

OperationalError: (psycopg2.OperationalError) 无法连接到服务器:连接被拒绝服务器是否在主机localhost"(::1) 上运行并接受端口 5432 上的 TCP/IP 连接?无法连接到服务器:连接被拒绝服务器是否在主机localhost"(127.0.0.1)上运行并接受端口 5432 上的 TCP/IP 连接?

OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? 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?

这表明 Docker postgresql(正在运行)在该端口不可用.我尝试将 -p 5432:5432 添加到我的 docker-compose exec 中,但没有成功.有小费吗?

Which suggests the Docker postgresql (which is running) isn't available at that port. I've tried adding -p 5432:5432 to my docker-compose exec without success. Any tips?

推荐答案

由于您的flask 应用程序和 Postgres 图像不在同一个 docker 容器中,您无法通过 localhost 访问数据库!!

As your flask app and Postgres images are not in the same docker container you cannot access the database via localhost !!

在您的数据库 URL 中替换 localhost docker-compose/中 Postgres 服务的名称

in your database URL replace localhost the name of Postgres Service in docker-compose/

engine = create_engine('postgresql://user:user_password@{}:5432/database'.format('service_name_of_postgres'))

赞这个答案.

这篇关于如何使用 sqlalchemy 在 Docker 中访问 postgresql?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆