How to connect to Postgres database on Docker in W

2019-07-10 07:36发布

问题:

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

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()

Then I'm getting this error:

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?

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.

回答1:

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

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"

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.

Finally the correct command :

engine = create_engine('postgresql+psycopg2://postgres:mysecretpassword@192.168.XX.XXX/mydb?port=5430')


回答2:

Not sure if this is just a typo in your example, but you are mapping your postgres container in your first code snippet to port 5430. If this is correct you will have to change your connection string to the following:

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