2

I'm a little lost as to why my java application can't connect to my postgres database. I'm aiming to connect to a postgres database through jdbc. The application is to run inside a docker container.

this.connection = `DriverManager.getConnection("jdbc:postgresql://<myip>:5432/databasename", "usr", "password");`

I'm getting the exception:

Connection refused.  Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

When I run the application from my desktop, it connects as expected. When I run it from within the docker container, it fails.

I've just installed docker this afternoon and ran through the getting started for windows, so my setup state is just after running that. Here's the contents of my Dockerfile:

FROM java:8
ADD VaultServer /
EXPOSE 3971
EXPOSE 3972
ENTRYPOINT ["java", "-jar", "VaultServer.jar"]
Andy
  • 3,228
  • 8
  • 40
  • 65
  • 1
    Have you configured the [pg_hba.conf](http://www.postgresql.org/docs/9.1/static/auth-pg-hba-conf.html) file properly in order to accept connections from the docker container's IP address? – dic19 Mar 31 '16 at 14:35
  • I think so. It's an installation on my local machine which I haven't modified since it was initially created by the default process. It just has the following in it: # IPv4 local connections: host all all 127.0.0.1/32 md5 # IPv6 local connections: host all all ::1/128 md5 – Andy Mar 31 '16 at 14:48
  • 1
    It seems that you want to connect to a PostgreSQL installation on the host from an application inside a Docker container. If that is the case, read here http://stackoverflow.com/questions/31249112/allow-docker-container-to-connect-to-a-local-host-postgres-database – Xiongbing Jin Mar 31 '16 at 15:36

1 Answers1

5

Inside the data folder there is a file called pg_hba.conf you have to configure it to accept the connections. So your pg_hba.conf file should have a line like this host all all YourDockerip/24 md5.

After that configure the postgresql.conf file. You have to update the listen_addresses to all and make sure to uncomment that line by removing the # mark. So your listen_addresses should look like this listen_addresses = '*'.

chalitha geekiyanage
  • 6,464
  • 5
  • 25
  • 32
  • 1
    Sorry I'm still getting my head around docker. Do you mean the ip for the docker machine, or the ip for the container? If it's the latter; is there some way to listen to any/all from docker, as I'm intending to eventually dynamically spin these containers up and down. – Andy Mar 31 '16 at 14:57
  • 2
    To listen to all ip addresses you can use `0.0.0.0/0`. Did you restart the postgreSQL server after configuring the files? – chalitha geekiyanage Mar 31 '16 at 15:07