john chesley

fresh stuff

destinations

favorites

using an ssh tunnel to connect to postgres

this is a nifty trick:

i have a postgres database server on a remote machine. it doesn't accept connections from the outside world, and doesn't really need to, either, since it just runs some local stuff, my django apps, and other random things that i do with it now and then.

while quite secure, it can be hard to work with, as until i discovered this trick i had to log in to that machine to access the server. even then i was limited to the command-line interface, which takes more getting used to than i've done yet. this command, however, allows me to connect from my laptop over a secure connection, without telling the database server to accept connections from the outside:

ssh -L 4001:127.0.0.1:5432 remotehost

this sets up an ssh tunnel, which accepts connections on port 4001 of the local machine/laptop/etc, and forwards that connection over an encrypted "tunnel" to remotehost. from there the connection gets forwarded to the host and port you specify (here i specified 127.0.0.1:5432, postgres' default) the postgres server thinks the connection is coming locally from the machine it is running on, and meanwhile you can use whatever local client you want to connect, without opening up the server to the world. just specify localhost as the server, on port 4001, and you're golden.

beauty, eh?