本文介绍了如何使用SQLAlchemy在Windows 10中的Docker上连接到Postgres数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Docker和以下命令在计算机上建立了一个临时的Postgres数据库,用于测试:

I have set up a temporary Postgres database for test purposes on my computer using Docker and the following commands:

1)

sudo docker run --name some-postgres6 -e POSTGRES_PASSWORD=mysecretpassword -p 5430:5432 postgres:9.1 -d postgres

2)

sudo docker run -it --rm --link some-postgres6:postgres postgres psql -h postgres -U postgres

我要使用Python连接到数据库:

I want to connect to the database using Python :

from sqlalchemy.engine import create_engine
import psycopg2

engine = create_engine('postgresql+psycopg2://postgres:mysecretpassword@localhost/mydb?port=5432') ### IMPORTANT!!!
connection = engine.connect()

然后我得到这个错误:

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

同一段代码曾经在运行Ubuntu的另一台机器上运行。我想这与Windows有关。我正在运行Windows 10 Home(不具备Windows经验)并使用Docker工具箱。

This same piece of code used to work on my other machine where I was running Ubuntu. I guess this has to do with windows. I am running Windows 10 Home (not experienced with Windows) and using Docker toolbox.

推荐答案

我终于弄清楚了这个问题。它是 localhost ,在127.0.0.1上没有任何运行。

I finally figured out the issue. It was "localhost", there was nothing running on 127.0.0.1 .

我不得不将其更改为docker计算机的IP。如果打开 Docker快速入门终端,则会显示此信息。它显示类似 docker配置为使用IP 192.168.XX.XXX的默认计算机之类的内容。

I had to change it to the IP of the docker machine. This information is displayed if you open the Docker Quickstart Terminal. It shows something like "docker is configured to use the default machine with IP 192.168.XX.XXX"

另一个找到此IP的方法是打开 资源监视器 ,转到网络标签,然后检查 TCP连接 。应该运行 docker.exe 远程地址列中显示的IP是可以使用的IP。

Another way to find this IP is to open Resource Monitor, go to the Network tab, then check the TCP connections. There should be docker.exe running.The IP shown in the Remote Address column is the one that will work.

最后是正确的命令:

engine = create_engine('postgresql+psycopg2://postgres:[email protected]/mydb?port=5430')

这篇关于如何使用SQLAlchemy在Windows 10中的Docker上连接到Postgres数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 19:24