How to connect to PostgreSQL running in an Ubuntu VM
Posted by Diego em Setembro 19, 2016
FYI, PostgreSQL can be installed using:
sudo apt-get update sudo apt-get install postgresql postgresql-contrib
Optionally, install pgAdminIII (https://www.pgadmin.org/download/windows.php) .to test the connectivity.
Virtual Box creates virtual machines with the NAT network type by default. If you want to run server software inside a virtual machine, you’ll need to change its network type or forward ports through the virtual NAT.
With the NAT network type, your host operating system performs network address translation. The virtual machine shares your host computer’s IP address and won’t receive any incoming traffic. You can use bridged networking mode instead — in bridged mode, the virtual machine will appear as a separate device on your network and have its own IP address.
To change a virtual machine’s network type in VirtualBox, right-click a virtual machine and select Settings, go to “network” and change the “attached to” option to “Bridged Adapter”
You can check your VM’s new IP by typing “ifconfig” or clicking on the top right corner icon -> “System Settings” -> “Network”:
Then, navigate to Postgres’ installation folder (normally on: /etc/postgresql/9.5/main) and edit the postgresql.conf file setting it to whatever suits you (I set it to all):
sudo vi postgresql.conf
sudo systemctl restart postgresql #restart
That will make PostgreSQL to listen to all IPs, as we can see on this before\after:
(That will allow you to connect locally using the server’s IP address, before this step you’d be able to connect only using “localhost”).
At last, edit the pg_hba.conf (https://www.postgresql.org/docs/9.5/static/auth-pg-hba-conf.html ) file, which controls client authentication, and add a row that allows all connections:
sudo vi pg_hba.conf
sudo systemctl restart postgresql
By doing so, you should be able to access PostgreSQL from outside your VM.