How to connect with host PostgreSQL from vagrant virtualbox machine

PostgresqlNetworkingUbuntu 12.04VirtualboxVagrant

Postgresql Problem Overview


I have a VirtualBox machine running Ubuntu 12.04 in a Mac OS X host machine. In my host machine (Mac OS X), I have PostgreSQL installed. I would like to connect to this PostgreSQL server from my Ubuntu virtual machine (I know normally it's the opposite way).

I guess I should configure some networking parameters in VirtualBox itself. All I get from Vagrant docs is I need to assign my vm a static IP to use a private network. But once created, how do I reach my host from my guest?

I didn't find anything like that in vagrant docs. So, there's probably a good reason for that. Does it make sense? I don't want to duplicate PostgreSQL installation. Just use my current existent one.

Postgresql Solutions


Solution 1 - Postgresql

You can reach your host from your guest by using the default gateway on your VM.

See this answer for an explanation.

By running netstat -rn you can get the default gateway and then use that ip address in your config file of your application.

Running netstat -rn | grep "^0.0.0.0 " | cut -d " " -f10 should give you the correct ip address. (only tested this on my machine)

Solution 2 - Postgresql

Easy way - simply use this "magic" IP from inside of vagrant without any additional configurations:

10.0.2.2

Don't know if it's always static, though for me works and it's very convenient - I can use laptop at home, from office - having assigned different IPs to me by routers, but my VMs know the "trusty name" of their master 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJorge ArévaloView Question on Stackoverflow
Solution 1 - PostgresqlMatt CooperView Answer on Stackoverflow
Solution 2 - PostgresqlDaniel GarmoshkaView Answer on Stackoverflow