Port Forwarding for SSH & HTTP on VirtualBox

When we do software emulations in custom environments for testing and experimental purposes, we often depend on a Virtual Machine (VM) option like Oracle VirtualBox or VMWare, rather than using physical machines or cloud-based clusters. In general, a VM acts as a separate physical computer which resides inside our host computer consuming a proportion of host machine resources such as RAM, Storage, Display, Network etc.

Each VM has its own OS environment and can work independently as a separate physical machine. But mostly we only need the terminal access to execute some bash scripts and get our work done using the programs running on these VMs. Also if we can emulate the VM in headless mode (no GUI) by installing the server version of our preferred OS distribution, we can minimize the overall hardware footprint too.

On Oracle VirtualBox, we can let our VM work as a server in headless mode and login to it from the host machine to perform operations via SSH or even serve a web app through VM and view it on the host’s web browser. Let’s see how we can configure these settings.

Configuring SSH

SSH is a secure network protocol widely used for remote login to a computer system by its privileged users. Let’s configure SSH access to guest system from our host machine with the following steps:

01) Start the guest VM and install openssh-server on guest machine. If you are on a Debian/Ubuntu VM, you can follow with my terminal commands:

sudo apt-get install openssh-server

02) Now make sure your SSH service is running in your background:

sudo service ssh status

active (running) label in green color indicated that the SSH works fine on the system.

03) Check the local IP address of the guest VM:

hostname -I

Port Forwarding

Now while your VM is running, right click and open the Settings window.

Select the Networktab and expand the Advancedsection. While keeping theCable Connected option checked, click on Port Forwarding button.

Click on the green + icon in right side and add port forwarding rules for SSH and HTTP.

Port 22 is the default SSH port and the port 80 is reserved for HTTP serving. Now what we have done is, asking the idle port 2200 of our host machine to listen to the port 22 of the guest VM. So through the localhost of our host machine, we can remote login to VM. On the other hand, the same has done for the HTTP serving. On the host machine by navigating to http://localhost:8000 , we can view anything serving in the VM through port 80. Likewise, we can write several port mapping rules for different protocols.

To make sure that your configurations are working fine, fire up the terminal in your host machine and try to remote login to the VM:

ssh -p 2200 ashenwgt@localhost