# How to connect to your PostgreSQL database remotely

Connect a database client on your own computer (for example pgAdmin, DBeaver or `psql`) to a
PostgreSQL database on your host. The recommended, secure way is an SSH tunnel.

## Why the database port is not open by default

For security, PostgreSQL listens on `localhost` only (`postgresql_listen_addresses: "localhost"`), so
the database port is not reachable from the internet. Rather than exposing it, you forward it over
your existing SSH access - the connection is encrypted and uses your SSH key.

## Connect over an SSH tunnel (recommended)

1. Open a tunnel from a local port (here `5433`) to the database on the host:
   ```bash
   ssh -L 5433:127.0.0.1:5432 prod@web1.example.com
   ```
   Leave this session open while you work.
2. Point your client at the local end of the tunnel:

   | Setting | Value |
   | --- | --- |
   | Host | `127.0.0.1` |
   | Port | `5433` |
   | User (role) | your database role (from [Credentials](../../platform/hosts/credentials.md)) |
   | Password | the role's password |
   | Database | your database name, for example `prod_db` |

pgAdmin and DBeaver can also create the SSH tunnel for you - set the SSH host and key, then set the
database host to `127.0.0.1`.

## Opening the port instead (advanced)

If a tool genuinely cannot tunnel, you can widen access - but this exposes the database, so prefer the
tunnel.

- Widen `postgresql_listen_addresses` and add host-based rules with `postgresql_extra_access` for the
  specific networks or hosts that need it (see [Configure PostgreSQL](configure.md)).
- Also allow the exact source IP addresses on the host's **Security** tab
  ([Security](../../platform/hosts/security.md)).
- Connect with a [least-privilege role](manage-database-users.md), never the application's main role.

> [!WARNING]
> Never open the database broadly. Grant access only to specific, trusted hosts, and use a dedicated
> limited role.

## Troubleshooting

- **Connection refused** - the tunnel is not open, or the client is pointing at the host instead of
  `127.0.0.1`.
- **Authentication failed** - wrong role/password, or no matching host-based access rule (see
  [Create and manage PostgreSQL users](manage-database-users.md)).
- **Times out when opening access directly** - the source host is not allowed, or
  `postgresql_listen_addresses` is still local. See
  [Database problems](../../troubleshooting/database-issues.md).

## Related

- [Configure PostgreSQL](configure.md)
- [Create and manage PostgreSQL users](manage-database-users.md)
- [Import and export a database](import-export-database.md)
- [SSH access](../../platform/hosts/ssh.md)
- [Host Security tab](../../platform/hosts/security.md)
