There’s two common ways one can connect to RDS:
- Write inbound rules to allow an IP to connect to RDS (IP Whitelist). However, IPs constantly change, so very quickly this will become a chore.
- Use an SSH Tunnel
This guide will help you set up an SSH Tunnel, and then use it to connect to your remote RDS instance through Sequel Pro, or the Terminal.
As always, please leave a comment if you have any issues with this guide, and I’ll do my best to help out.
Set up an SSH Tunnel
Essentially what we will do, is connect to RDS through a Webserver that already has access to the database. We will map a local port, to the remote port RDS listens to for connections, and connect to RDS through the Webserver that hosts your application, and already has access to RDS.
This is a template of the command:
ssh -N -L localPort:rdsHost:remotePort user@remoteHost -i ~/path/to/key
do not execute a remote command (useful for forwarding ports)-L
forward localPort to remotePortlocalPort
the port your local database connects to. You can set this to any available port such as 1234, 3306 and so on. rdsHost
your RDS endpoint (url)remotePort
the port your remote database listens to for connections. For MySQL databases the default is 3306. For PostgreSQL databases, the default is 5432.user@remoteHost
the username and the remote instance your tunnel will connect to the database through. These are the credentials you use to ssh into your web server (ec2)-i
identity (key file)
ssh -N -L 1234:my-awesome-rds.us-east-1.rds.amazonaws.com:3306 janeDoe@ec2server.com -i ~/.ssh/AwesomeServerKey.pem
Running this command “opens” the ssh tunnel, which I can now use. For convenience, I’d recommend setting up an alias for this command.
Use an SSH tunnel
Connect using SequelPro
To connect with SequelPro, specify the localPort from earlier (1234), and connect through localhost (127.0.0.1) using your RDS username and password.
Connect using the Command Line
mysql -u awesomeRdsUsername -p -h 127.0.0.1 -P 1234