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.

R. Jutras
  • 331
  • 1
  • 4
  • 14

1 Answers1

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!

Community
  • 1
  • 1
Andy Shinn
  • 26,561
  • 8
  • 75
  • 93