Allow Linux in VirtualBox to connect to the localhost of the host machine

In this article I’ll show you how to set up a Linux running in VirtualBox to be able to access a service running on localhost on the host machine. I’ll use MySQL as an example, because that was the problem I faced with. The Linux OS of my choice is Ubuntu.

Testing the connection

First, let’s see how you can test if your virtual machine can access the service on the host. There is a great program called nmap for it. If it is not installed, you can install it with the following commands:

sudo apt-get update
sudo apt-get install nmap

Let’s suppose we have a web application that is trying to connect to the MySQL server on localhost:3306 by default. We would not like to change this configuration, but allow our virtual linux to connect to the MySQL server running on the host.

So, first let’s check if we can connect to MySQL:

nmap -p 3306 localhost

You could see something like this, indicating that it cannot connect:

Starting Nmap 7.01 ( https://nmap.org ) at 2016-09-18 19:12 CEST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000053s latency).
PORT     STATE  SERVICE
3306/tcp closed mysql

You should see an “open” STATE in the output instead of “closed”. Let’s try to resolve that.

Map localhost in the hosts file

We would like for our virtual linux to map localhost calls to the host machine. For this, we have to determine the default gateway of our machine.

netstat -rn
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
0.0.0.0         10.0.2.2        0.0.0.0         UG        0 0          0 enp0s3
10.0.2.0        0.0.0.0         255.255.255.0   U         0 0          0 enp0s3
169.254.0.0     0.0.0.0         255.255.0.0     U         0 0          0 enp0s3
root@relevart-VirtualBox:/media/sf_Projects/Java/#

Check the Gateway in the 0.0.0.0 line. That 10.0.2.2 IP address is what we need.

Open /etc/hosts and comment out the default line for localhost mapping and add a new one like this:

#127.0.0.1 localhost
10.0.2.2  localhost

After saving the file, and running nmap again, you should see that the STATE of the port is “open”.