Delinea Blog > How to connect to a remote PostgreSQL database

How to connect to a remote PostgreSQL database

Published December 2024
Read time 6 minutes
What you will learn
Need to connect to a remote PostgreSQL database? We discuss four easy methods to do so, how to troubleshoot common issues you may encounter, and best practices to implement.

Connecting to a remote PostgreSQL database can prove daunting for some teams. Your organization risks losing valuable time, which then leads to lost productivity.

There are four methods for connecting to a remote PostgreSQL database: psql, pgAdmin, a third-party client such as DBeaver, or a driver in your application code. All four need the same two configuration changes on the server first, and all four carry the same risk if you make those changes as most tutorials describe.  

What you need before you connect to a remote PostgreSQL database

Before you start, confirm you have:

  • PostgreSQL installed and running on both the client machine and the server.
  • a client-installed pgAdmin, psql, or any third-party tool such as DBeaver.
  • the connection details including the database name, hostname, port, username and password.

Configuring PostgreSQL for remote connections

PostgreSQL accepts only localhost connections by default. Two configuration files change that. 

Editing postgresql.conf

This adjustment enables connections beyond the local machine:

  1. Locate the postgresql.conf file in /etc/postgresql/16/main/ on Ubuntu, or /var/lib/pgsql/data/ on Red Hat derivatives, and open it in a text editor.
  2. Set listen_addresses to the address the server should accept connections on, for example listen_addresses = '10.0.4.12'. Use '*' only when a firewall already restricts who can reach port 5432.
  3. Save your changes and close the text editor. 
  4. Run the following command to restart PostgreSQL: "sudo systemctl restart postgresql."

Modifying pg_hba.conf

The pg_hba.conf file controls which users can connect, from which addresses and with which authentication method. 

  1. Open the "pg_hba.conf" file  in /etc/postgresql/16/main/. 
  2.  Add an entry that names the subnet your clients connect from and uses scram-sha-256: 
# IPv4: one application subnet, not the whole internet
host all all 10.0.4.0/24 scram-sha-256
# IPv6: the equivalent scoped prefix
host all all 2001:db8:4::/64 scram-sha-256

Changing the method in pg_hba.conf does not re-hash existing passwords. Set password_encryption = 'scram-sha-256' in postgresql.conf, restart, then have each user set their password again so the new hash is stored. Skip that step and those users can no longer log in.

Sec the connection at the network layer

Allowing remote connections to a PostgreSQL server exposes it to anyone who can route to port 5432. Three controls narrow that exposure.

Configuring firewall rules

Configure the server's firewall to allow traffic on PostgreSQL's port, 5432 by default, and only from the addresses that need it.

On a Linux server, ufw does this:

sudo ufw allow from 10.0.4.0/24 to any port 5432 proto tcp

Or with iptables:

iptables -A INPUT -p tcp -s 10.0.4.0/24 -m state --state NEW --dport 5432 -j ACCEPT

For cloud environments, you can adjust the security group settings or firewall rules within the cloud platform's management console.

Using a VPN or SSH tunnel

Using a VPN, you can keep PostgreSQL's default firewall settings and even limit its "listen_addresses" to localhost. With a VPN, the database isn't directly exposed to the public internet.

SSH tunnels forward traffic from a local port on your machine to the PostgreSQL server over an encrypted connection, which protects data in transit. 

Open the tunnel:

ssh -L 5432:localhost:5432 user@remote_host

Then connect to localhost on port 15432. The published example used 5432 on both sides, which fails when PostgreSQL is already running locally on that port.

Four ways to connect to a Remote PostgreSQL database

With the server configured and the network restricted, connect using whichever method fits your work. 

1. Using psql

psql takes the connection details as flags: 

psql -h <host> -p <port> -U <username> -d <database>

When you press Enter, you'll receive a prompt to enter your password for authentication.

2. Using pgAdmin

  1. Launch pgAdmin from your computer and click the "Add New Server" option.
  2. Fill in the required information on the "Connection" tab at the top of the server screen.
  3. Click "Save."

3. Using third-party clients such as DBeaver

  1. Launch the DBeaver application, select "Database," and then choose "New Database Connection."
  2. Choose "PostgreSQL," and then enter the connection credentials.
  3. Click "Test Connection" to verify the connection, then "Finish," and the application will connect you to the database.

4. Connecting from application code

Each driver takes the same connection details. Read the password from the environment rather than writing it into the file:

Python

import psycopg2               
conn = psycopg2.connect(
         host="remote_host",
         database="db_name",
         user="username",
         password=os.environ["DB_PASSWORD"],

Node.js

const { Client } = require('pg'); 
const client = new Client({
host: 'remote_host',
database: 'db_name',
user: 'username',
  password: process.env.DB_PASSWORD,          
});
client.connect();

Java

Connection connection = DriverManager.getConnection(                         
      "jdbc:postgresql://remote_host:5432/db_name",
"username", System.getenv("DB_PASSWORD"));

To connect to PostgreSQL, you need the PostgreSQL JDBC driver. Therefore, include it as a dependency in your project.

Common errors and how to fix them

When connecting remotely, you may encounter authentication issues for several reasons, including wrong username/password combinations or incorrect "pg_hba.conf" settings. 

If you receive a "connection refused" message, it might be because you haven't configured PostgreSQL to listen to the right IP addresses or your firewall to allow traffic on port 5432. 

For an incorrect client authentication configuration:

  • Locate the "pg_hba.conf" file on your PostgreSQL server. It's typically found in the data directory. For example, "/var/lib/postgresql/ 16/main/.
  • Check for a rule allowing connections from your client’s IP address and add one if it is missing:
"host    all    all    203.0.113.25.32  scram-sha-256
  • Save the changes and restart PostgreSQL: "sudo systemctl restart postgresql."

Five practices that keep the connection secure

Password complexity does the least work on this list, because a password that never changes and is shared across a team fails whatever its length. These five do more:

  • Use the principle of least privilege (PoLP) at the database role, not just the network. A reporting user needs SELECT on named tables, not the rights granted by a superuser role. 
  • Use SSL/TLS to encrypt traffic between the client and server by updating postgresql.conf with ssl = on.. That setting alone is not enough: the server needs a certificate and key, and clients need sslmode=verify-full so they actually check it. Without that, a client accepts any certificate presented to it.
  • Review and deactivate any user accounts that are no longer in use.
  • Restrict access to the PostgreSQL server by allowing only trusted IP addresses to connect. This can be managed through firewall rules or PostgreSQL's "pg_hba.conf" file.
  • Bind the PostgreSQL service to a specific IP address rather than listening on all interfaces (0.0.0.0). Configure this in the "postgresql.conf" file

What can't be fixed: the credential

 Every method above ends the same way: a password typed at a prompt, saved in a client profile or read from a file on a developer's laptop. That password is usually shared, rarely changed and attached to no particular person. None of the network controls above touch it. 

That is the gap Delinea Secret Server fills for a PostgreSQL account. Its PostgreSQL password changer lets you:

  • store the database credential in the vault rather than in a .env file or a saved DBeaver profile.
  • verify it with a heartbeat, which tells you when a credential has been changed out from under you.
  • change it on demand from the secret, so rotating after someone leaves is one action rather than a hunt through every client that stored it.
  • record who checked it out, which turns "the reporting account ran that query" into a named person.

Least privilege governs what the database role can do. Identity governs who is behind the credential. The information above covers the first. The second needs something outside PostgreSQL.

See how a vaulted database credential works: book a demo today.

 

Related Topics