Loading...

Connect to a remote PostgreSQL database from Terminal or from other machine

It's been a while since I wrote something. Just this topic tempted me to write. We are having an app which uses postgres database. So initially we were using database and app in same machine. Due to performance requirements, we wanted to have app and db separately. So, my colleague installed app in a ec2 instance and postgresql in another instance. He was struggling to connect each other. It's quite easy if it is in same machine. We just need to give postgres install path (usually takes it default). But when it's another host, you need to perform some additional step.

So, coming to installations, it's normal. Install postgres same way you do in any other machines. We use postgres 10 with ubuntu 18.04. Follow https://www.digitalocean.com/community/tutorials/how-to-install-and-use-postgresql-on-ubuntu-18-04 this guide to install postgres.

Once you installed, login to the machine you installed, and edit file - /etc/postgresql/10/main/postgresql.conf

Add/update following line: listen_addresses = '*' 

Update file: /etc/postgresql/10/main/pg_hba.conf

Add following line to end of the file with the ip from where you want to access: host    all             all             IP_OF_CLIENT_MACHINE/32        md5

Now restart postgres service:   systemctl restart postgresql

You are done, now you can access the database from clinet machine. Make sure to open the port in the postgres host machine

Test:

Local/host machine: psql -h localhost -U [db_user] -d [db_name]

Client machine: psql -h [HostIP] -U [db_user] -d [db_name]