How psql the database in a remote server using SSH tunnel?
$ ssh -nNT -L local-port:127.0.0.1:remote-port remote-db-user@remote-ip
$ psql -h 127.0.0.1 -p 9000 -U remote-db-user -d db-name
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
.
$ ssh -nNT -L 9000:127.0.0.1:5432 john@12.34.567.890
$ psql -h 127.0.0.1 -p 9000 -U john -d blog
The above command will prompt for john
password. See reference link below to learn how to set password for database user/role.
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.