5

I have used the following commands to create a Docker image with Postgres running on it:

docker pull postgres docker run --name test-db -e POSTGRES_PASSWORD=my_secret_password -d postgres

I then created a table called test and inserted some random data into a couple of rows. I am now trying to make a connection to this database table through psycopg2 in Python on my local machine. I used the command docker-machine ip default to find out the IP address of the machine as 192.168.99.100 and am using the following to try and connect:

conn = psycopg2.connect("dbname='test-db' user='postgres' host='192.168.99.100' password='my_secret_password' port='5432'")

This is not working with the error message of "OperationalError: could not connect to server: Connection refused (0x0000274D/10061)"

. .

Everything seems to be in order so I can't think why this would be refused. According to the documentation for this postgres image, (at https://hub.docker.com/_/postgres/) this image includes EXPOSE 5432 (the postgres port) and the default username is postgres.

I also tried to get the IP address of the image itself with docker inspect test-db | grep IPAddress | awk 'print{$2}' | tr -d '",' that I found on SA to a slightly related article, but that IP address didn't work either.

1
  • Have you tried connecting with a different client like psql? Commented Jan 21, 2016 at 1:12

1 Answer 1

7

The EXPOSE instruction may not be doing what you expect. It is used for links and inter-container communication inside the Docker network. When connecting to a container from outside the Docker bridge network you need to publish to port with -p. Try adding -p 5432:5432 to your docker run command so that it looks like:

docker run --name test-db -e POSTGRES_PASSWORD=my_secret_password -d -p 5432:5432 postgres

Here is a decent explanation of the differences between publish and exposed ports: https://stackoverflow.com/a/22150099/684908. Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.