background image
HomeRecent PostsDrupalSearchTagsRSSContactAboutAccount

Setting up NAT and port forwarding to connect to a VirtualBox virtual machine for LAMP development

Eric.London's picture

I recently got a new MacBook Pro laptop (awesome!) and went through my usual rigmarole of setting up a new [VirtualBox] virtual machine for LAMP development. In previous situations I used bridged network connections which allow my virtual machine to have its own network connection, and acquire an IP address via DHCP. Now that I plan on being more mobile, I was concerned about having a static IP address for my virtual machine (for samba connections, scripting, and any other processes that relies on a static IP address). I decided to explore alternative virtual network connections and changed my virtual NIC to use NAT (the default network connection for VirtualBox). This configuration establishes a virtual NAT for your virtual machines which is great, but the downside is I know have to setup port forwarding to connect to my virtual machine. In bridged network configurations, I could simply SSH or use Samba to connect to my virtual machine by IP address. With NAT I have to setup port forwarding for the services I need to connect to. Initially I decided to setup port forwarding for SSH (port 22) and HTTP (port 80). While my virtual machine was powered down, I executed the following commands. NOTE: you'll have to replace "Centos" with the name of your virtual machine.

$ VBoxManage setextradata "Centos" "VBoxInternal/Devices/pcnet/0/LUN#0/Config/guestssh/Protocol" TCP
$ VBoxManage setextradata "Centos" "VBoxInternal/Devices/pcnet/0/LUN#0/Config/guestssh/GuestPort" 22
$ VBoxManage setextradata "Centos" "VBoxInternal/Devices/pcnet/0/LUN#0/Config/guestssh/HostPort" 2222
$ VBoxManage setextradata "Centos" "VBoxInternal/Devices/pcnet/0/LUN#0/Config/guesthttp/GuestPort" 80
$ VBoxManage setextradata "Centos" "VBoxInternal/Devices/pcnet/0/LUN#0/Config/guesthttp/HostPort" 8080

Now, I can SSH to my virtual machine..

$ ssh -p 2222 Eric@localhost

Or, connect to Apache by browsing to http://localhost:8080

The benefit of this network configuration allows me to travel anywhere with my laptop, use any type of network connection, and not have to worry about changing the way I connect to my virtual machine for development.

port forwarding ip addresses

I've been trying to do the same thing, however can't seem to get it to work. Your host machine would have the 127.0.0.1 IP address. What is the IP address for your virtual machine?