Search code examples
amazon-web-servicesamazon-rdsknex.jsssh-tunnel

knexjs use SSH tunnel to connect local to EC2 jump host (connects to RDS)


I've been at this for some time. I'm attempting to use knexjs and ssh2node libraries to connect my local to my RDS instance via an EC2 jump host. I am able to connect via SSH (in my termal and on dbeaver) into my ec2 instance which talks to my RDS database. I also notice SSH works in my code as well but I can't seem to find a way to make knexjs use my ec2 instance to connect, does anyone have any pointers?


Solution

  • The easiest method is to use SSH with Port Forwarding. You don't say which database you are using, so let's assume port 3306:

    ssh -i key.pem -L 3333:mydatabase.123456789012.us-east-1.rds.amazonaws.com:3306 ec2-user@EC2-IP-ADDRESS-OR-DNS-NAME
    

    This will forward any requests sent to local port 3333 (you can use any port number) to the EC2 instance, where it will then be forwarded to mydatabase.123456789012.us-east-1.rds.amazonaws.com:3306.

    You can then point your SQL client to:

    localhost:3333
    

    That will connect it to the remote database.