如何使用 sqlalchemy 在 Docker 中访问 postgresql?

编程入门 行业动态 更新时间:2024-10-25 12:27:59
本文介绍了如何使用 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?

本文发布于:2023-10-16 16:52:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1498168.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   sqlalchemy   postgresql   Docker

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!