Every time I go to set up VirtualBox and several VMs I always forget how I setup the networking for them. Once again, I went through the pain of trying to figure it all out, so I might as well document it for future use.
When creating virtual machines, especially virtual linux servers, I want them to be able to do the following things:
Out of the box, a VM is configured for #1, however it cannot do #2 and #3. There are some solutions that do some archaic port forwarding by issuing special commands from the Terminal. This is just painful, and if you just want one port to work, that’s manageable, but what if you want ssh, ftp, myql, http, https, etc? Any on multiple VMs? What a nightmare! What is painful is when googling for a solution, almost every “answer” is this crazy port forwarding method. There is a much cleaner, better way!
Go into your VM’s settings and go to “Network”, it will list options for 4 different adapters. Instead of hacking one adapter to do all the work, just setup more adapters for your configuration. For adapter #2, set it to Host-only. This enables an IP range for communicating from the Host to the Guest and vice versa. Start up your VM, and if you are using something like Ubuntu, edit your /etc/network/interfaces file so it looks like this:
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
# The loopback network interface
iface lo inet loopback
# The primary network interface
iface eth0 inet dhcp
### ADD THESE LINES
iface eth1 inet dhcp
After adding these lines, run the command:
sudo /etc/init.d/networking restart
Now VirtualBox is configured to host this traffic over the 192.168.56.x IP range (I’m not sure if/where you can change this). So do an ifconfig on your guest machine, and it should show you the IP it has been assigned. If you want, you can change your /etc/network/interfaces so it can be statically assigned. You should now be able to SSH into your box on it’s IP:
ssh -l justin 192.168.56.101
Now, what if I have a Cassandra server, a Web Server, and a MySQL server each on their own VMs. What you do is create a third adapter set to “Internal Network”. Then in your /etc/network/interfaces file you set eth2 to a static IP of your choosing. I typically use the 10.0.0.x range. So each server is respectively 10.0.0.10, 10.0.0.20, and 10.0.0.30. However, over the 10.0.0.x range there is no DHCP, no Gateway, no nothing, just direct communications over these IPs.
So please, for the love of everything good, don’t resort to crazy port forwarding, complicated XML file editing, solutions for VirtualBox. Just use each type of interface configuration for what you need. Thank you!