Skip to content

Instantly share code, notes, and snippets.

@Rulinski
Forked from zulhfreelancer/ssh-tunnel.md
Created September 7, 2018 06:25
Show Gist options
  • Save Rulinski/1efc3c6d8ae63c90751a54daa924da85 to your computer and use it in GitHub Desktop.
Save Rulinski/1efc3c6d8ae63c90751a54daa924da85 to your computer and use it in GitHub Desktop.
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 [email protected]

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:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment