3

I got postgres.app running locally on my Mac and would like my local docker container to be able to connect to it. How do I best do this?

I found this post that suggests to pass the Docker host’s IP address to a container using the --add-host flag (Host port with DB to Docker container). However, my laptop's IP address changes frequently. Isn't there an easier way of doing this? Isn't there an easy way to open a local port to a container?

Community
  • 1
  • 1
Malte
  • 337
  • 1
  • 11
  • You can also use the network address of the host in the subnetwork of docker containers, which is `172.17.0.1` by default. It works nicely on a Linux host, but I am not sure that would work on a Mac. – bekce Feb 28 '17 at 06:56
  • @bekce That sounds like I'd like to give that a try. Any pointers as to how to use the network address of my host in the subnetwork of my docker container? – Malte Feb 28 '17 at 09:07
  • Well, just try `docker run -it --rm ubuntu`, once inside: `apt update && apt install telnet && telnet 172.17.0.1 5432` and see whether it can connect or not. – bekce Feb 28 '17 at 12:01
  • Thanks! I figured out how to do this and ... the connection was refused. – Malte Mar 01 '17 at 10:50

3 Answers3

4

Few things

  • Use docker.for.mac.localhost as your HOST (This assumes you have the latest Docker for Mac as @Pete mentioned)
  • Make sure there is such a record in ~/Library/Application Support/Postgres/var-9.6/pg_hba.conf

host all all 0.0.0.0/0 trust

  • Change this line listen_addresses = 'localhost' in ~/Library/Application Support/Postgres/var-9.6/postgresql.conf

to

listen_addresses = '*'

or

listen_addresses = 'localhost, docker.for.mac.localhost'

Nour Wolf
  • 2,140
  • 25
  • 24
0

If we are talking about a developers workstations, you could start your Docker Container inside the Host Network.

docker run --net=host myContainer

So your container runs in the same stack as your Host, and should be able to access your postgres.app.

opHASnoNAME
  • 20,224
  • 26
  • 98
  • 143
0

From your container, try connecting to hostname docker.for.mac.localhost. For example:

psql -U my_user docker.for.mac.localhost -U my_user my_database

From the docs:

The Mac has a changing IP address (or none if you have no network access). From 17.06 onwards our recommendation is to connect to the special Mac-only DNS name docker.for.mac.localhost which will resolve to the internal IP address used by the host.

Note: this requires Docker for Mac >= 17.06.0-ce-mac18, 2017-06-28

Pete
  • 10,310
  • 7
  • 53
  • 59