zulhfreelancer
8/28/2018 - 6:46 PM

How psql the database in a remote server using SSH tunnel?

How psql the database in a remote server using SSH tunnel?

Format

First terminal (dev machine):

$ ssh -nNT -L local-port:127.0.0.1:remote-port remote-db-user@remote-ip

Second terminal (dev machine):

$ psql -h 127.0.0.1 -p 9000 -U remote-db-user -d db-name

Example

Assuming the remote host IP address is 12.34.567.890 and we want to connect to Postgres running inside it on port 5432. We can SSH tunnel into it from our dev machine on port 9000.

Assuming the database user/role is john and the database that we want to connect to is called blog.

First terminal (dev machine):

$ ssh -nNT -L 9000:127.0.0.1:5432 john@12.34.567.890

Second terminal (dev machine):

$ psql -h 127.0.0.1 -p 9000 -U john -d blog

Notes

  1. The above command will prompt for john password. See reference link below to learn how to set password for database user/role.

  2. Postgres is using 'ident authentication' which means the database user/role is also a Linux user. In this case, the Linux user is john and the database user/role is also john. See reference link below to learn how to add user.

References: