In this short post I will show you how you can allow connections to your PostgreSQL from outside, for example, using tools like pgAdmin, inside an Azure VM.
When you first install your Postgres, by default, the only entity allowed to connect to it is the machine it runs on (localhost). So here are the steps needed to allow remote connections.
Edit postgresql.conf file
sudo nano /etc/postgresql/12/main/postgresql.conf
note: your path might be different, so please check where your conf file is first
Find the line with listen_addresses in it. If it’s commented – uncomment it by removing the ‘#’. Then change it to this:
Note that the ‘*’ allows all IP addresses, which is not a good practice, so it’s better to use your own public IP address in here.
CTRL + O *ENTER* CTRL + X
to save and close nano
Edit pg_hba.conf file
sudo nano /etc/postgresql/12/main/pg_hba.conf
note: your path might be different, so please check where your conf file is first
Find this line
Change it to this
CTRL + O *ENTER* CTRL + X
to save and close nano
Allow inbound port in Azure portal
Since we’re using Azure VM we need to allow inbound port connection.
Assuming you already have a VM, click on it and go to Networking, under Settings.
Click on Inbound port rules and then on the right click on the button that says Add inbound port rule
Select PostgreSQL under Service and leave everything else as is then click Add.
Make sure the new rule appears on the screen.
Please note that here, again, it’s not a good practice to use Any as a Source as it will allow anyone who wants to try and connect. It’s better to use concrete IP addresses so that only specific IPs can try and connect as opposed to everyone who tries, like hackers. With Azure you can create virtual networks and there are better ways to handle stuff like that, but using concrete IP addresses is a step forward.
Restart the Postgres service in your VM
sudo service postgresql restart
After that you should be able to connect to your Postgres from outside the machine itself.
Hope that helps you in your journey, dear friend.