Port Forwarding Port Forwarding in Virtual Box - Postgres example

Virtual Machine localhost vs. Host localhost

If you are working with Virtual Machines, i.e. in Virtual Box, you will encounter the problem of not being able to access the VM. The only thing you need to do is to set correct port forwarding rules. Technically you need to map every VM port to a corresponding unoccupied(!) host port. Usually the VMs IP will be 10.0.2.15 but make sure to check it on Ubuntu with ifconfig amnd on Windows with ipconfig.

Changing VM network settings

If you would like to access i.e. the guest's postgres which usually runs on localhost port 5432 you need to map this port to your host under Virtual Box settings -> network -> adapter1 -> advanced -> port forwarding. Set your rules and pay attention that the host's port is not already occupied. Restart the VM and you should be able to access the VM's localhost. Note that in this example it is not 127.0.0.1 but 127.0.1.1. If for some reason you might not be able to set a new rule, make sure to set your connection type to NAT.

Accessing Postgres

You need to change two files to access Postgres from “outside”. Credits to stackoverflow community.

  1. In /etc/postgresql/12/main/pg_hba.conf (change to your postgres version number) add the following line at the very end host all all 0.0.0.0/0 md5
  2. In /etc/postgresql/12/main/postgresql.conf change the line listen_addresses = '*'.
  3. Restart postgres sudo service postgresql restart

Use locate on Ubuntu

If unsure where to find a file, just use locate postgresql.conf

On your host, this should connect to postgres on your guest VM.

1
psql -U postgres -h 127.0.1.1 -p 5432 postgres