PostgreSQL – Enable Remote Connections

By default, PostgreSQL server does not allow inbound connections over default port 5432. This means that only connections from the local machine can connect to the database. The following steps can be used to enable clients to connect over the network to PostgreSQL.

  • First, make sure that port 5432 is not blocked by any software firewall daemon. These steps will vary based on which operating system is in use. For example, on Red Hat Enterprise Linux (RHEL), you can use the following firewall-cmd commands to ensure that TCP port 5432 allows inbound traffic:
[postgres@dbtest ~]$ sudo lsof -i -P -n | grep "5432 (LISTEN)"
postgres   8090   postgres    6u  IPv4  50745      0t0  TCP *:5432 (LISTEN)
postgres   8090   postgres    7u  IPv6  50746      0t0  TCP *:5432 (LISTEN)

[postgres@dbtest ~]$ sudo firewall-cmd --zone=public --list-ports
[postgres@dbtest ~]$ sudo firewall-cmd --permanent --zone=public --add-port=5432/tcp
success
[postgres@dbtest ~]$ sudo firewall-cmd --reload
[postgres@dbtest ~]$ sudo firewall-cmd --zone=public --list-ports
5432/tcp
  • Next, find the postgresql.conf and pg_hba.conf file. On RHEL, running PostgreSQL 15, these can generally be found in /var/lib/pgsql/15/data. This is the same directory that is assigned to the $PGDATA environment variable.
  • Modify postgresql.conf. Look for the line containing listen_addresses='localhost' and replace it with listen_addresses='*'.
  • Modify pg_hba.conf, change the IP address mask in the IPv4 section to 0.0.0.0/0. This will allow inbound connections from any IP address. You could elect to be more specific here, but this ensures that anyone can access the database server.
  • Finally, restart PostgreSQL to apply the changes.
[postgres@dbtest ~]$ pg_ctl stop
[postgres@dbtest ~]$ pg_ctl start

Hope this helps,
Dustin

Leave a Reply

Your email address will not be published. Required fields are marked *