53

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.

Jorge Arévalo
  • 2,858
  • 5
  • 36
  • 44

2 Answers2

100

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)

Community
  • 1
  • 1
Matt Cooper
  • 9,962
  • 2
  • 31
  • 26
  • 1
    That command works for me too (guest == ubuntu/trusty64). Could connect to host mysql & ssh services (at least). – toddkaufmann Mar 17 '15 at 14:26
  • This doesn't work with the VMWare Ubuntu machines, unfortunately. I get a IP address but can't send connections through it, they're stuck in SYN_SENT. – Kevin Burke Sep 22 '16 at 05:22
36

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

Daniel Garmoshka
  • 5,849
  • 39
  • 40
  • 1
    I cannot explain why this is the default or how to customize it either, but I can confirm that on several of my machines I have this `ip route` entry: `10.0.2.0/24 dev eth0 proto kernel scope link src 10.0.2.15 metric 100` Meaning it seems to give the VM itself the address 10.0.2.15. Why .2 and .15 I don't know but just backing this up that Vagrant seems to be doing this automatically. – Jasmine Hegman Dec 22 '16 at 19:16
  • I think it's virtualbox default nat and network configuration doing this – Sebas Feb 02 '17 at 10:28
  • If someone wants to run the application from host as well as guest then we can use ipv4 address as database host. – Suraj Jul 24 '19 at 04:31