Enabling Remote Access to Postgres

To allow Postgres connections from a remote server, or from within a docker container, you’d want to allow it to listen to external traffic. This requires doing two settings, one in

# /etc/postgresql/15/main/postgresql.conf

listen_addresses = '*'
# This would listen to all addresses.
# Could also be set to 0.0.0.0 for the same effect.

and another in

# /etc/postgresql/15/main/pg_hba.conf

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
# host    all             all             127.0.0.1/32            scram-sha-256

# **Change:** Switched from 127.0.0.1/32 -> 0.0.0.0/0
host    all             all             0.0.0.0/0            scram-sha-256

# IPv6 local connections:
host    all             all             ::1/128                 scram-sha-256
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer

# **Change:** Switched to 0.0.0.0/0
host    replication     all             0.0.0.0/0            scram-sha-256

host    replication     all             ::1/128                 scram-sha-256

Note that you should ensure the safety of your database, when exposing it externally like this. Do use a firewall like ufw, or a VPN like tailscale to restrict access to your ports.


Tags
postgres

Date
November 6, 2023