Thursday, July 09, 2009

VirtualBox on CentOS 5.3: port forwarding

I have installed VirtualBox 2.2.4 on a CentOS 5.3. As a guest OS I installed Ubuntu, and on that Ubuntu I made a LAMP server. So, what I wanted was to redirect all html requrest on port 80 of CentOS (host) to port 80 of Ubuntu (guest). This is similar problem to the previously described on Windows XP host. The difference is that this time my host was CentOS 5.3, and VirtualBox was running as a normal user, not as a root.

The first thing to do was to make VirtualBox to forward the ports. I did it by executing the following commands, as a normal user under which VirtulBox was running. VBoxManage setextradata "ubuntu-server" "VBoxInternal/Devices/pcnet/0/LUN#0/Config/Apache/Protocol" TCP
VBoxManage setextradata "ubuntu-server" "VBoxInternal/Devices/pcnet/0/LUN#0/Config/Apache/GuestPort" 80
VBoxManage setextradata "ubuntu-server" "VBoxInternal/Devices/pcnet/0/LUN#0/Config/Apache/HostPort" 80
where "ubuntu-server" is the name of Ubuntu guest.

Than I wanted to start it in a headless modeVBoxHeadless -s ubuntu-server but I was getting the following error:Error: failed to start machine. Error message: NAT#0: configuration error: failed to set up redirection of 80 to 10.0.2.15:80. Probably a conflict with existing services or other rules (VERR_NAT_REDIR_SETUP).
Unknown error creating VM (VERR_NAT_REDIR_SETUP)
This error is due to the fact that in Linux systems only root can bind to ports below 1024, and not a normal user!. There are two possible solutions. First is to run VirtualBox as a root, the second is to redirect port 80 to port 8080 in the CentOS and the make VirtualBox to get connection from port 8080 of CentOS. I choose the second option. Therefore, I did as follows:

VBoxManage setextradata "ubuntu-server" "VBoxInternal/Devices/pcnet/0/LUN#0/Config/Apache/Protocol" TCP
VBoxManage setextradata "ubuntu-server" "VBoxInternal/Devices/pcnet/0/LUN#0/Config/Apache/GuestPort" 80
VBoxManage setextradata "ubuntu-server" "VBoxInternal/Devices/pcnet/0/LUN#0/Config/Apache/HostPort" 8080
The above makes VirtualBox to redirect trafic from 8080 of CentOS to 80 of guest ubuntu-server. Than as a root I used iptables to redirect port 80 to 8080 in CentOS iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080To check if iptables command was succesfull I used iptables -t nat -L commandiptables -t nat -L
Chain PREROUTING (policy ACCEPT)
target prot opt source destination
REDIRECT tcp -- anywhere anywhere tcp dpt:http redir ports 8080

Chain POSTROUTING (policy ACCEPT)
target prot opt source destination

Chain OUTPUT (policy ACCEPT)
target prot opt source destination
If OK save your iptables settings usingsudo /etc/init.d/iptables saveHope it will be useful. I also used VirtualBox 2.2, rather then VirtualBox 3.0, but I think the procedure will be similar.

The schematic illustration of what I did is below:



No comments:

Post a Comment