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 ( ) at 2016-09-18 19:12 CEST
Nmap scan report for localhost (
Host is up (0.000053s latency).
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         UG        0 0          0 enp0s3   U         0 0          0 enp0s3     U         0 0          0 enp0s3

Check the Gateway in the line. That 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:

# localhost  localhost

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