ssh tunnel for AWS RDS via bastion host to access in code directly

Once you have AWS RDS and bastion host created properly, you can connect to RDS database locally from your machine through IDE like MySQL Workbench, SQL Developer, putty or any other supported platform. But if you are developing code in any language like Java, python, .NET  or any other, then you need to set up a tunnel for connectivity from your machine. Use below syntax to create tunnel to host and then access in code as localhost or 127.0.0.1

Syntax
ssh -i “Private_key.pem” -f -N -L 3308:RDS_Instance_Endpoint:3306 ec2-user@EC2-Instance_Endpoint -v

Above, localhost port 3308 is forwarded to RDS instance port 3306 via EC2 bastion host using private key.

Once tunnel gets created, connect using mysql command from command prompt
Command
mysql –user=admin –password=”password” -h localhost DB -P 3308

In Intellij, use 127.0.0.1:3308 to connect to AWS RDS database. As long as tunnel is forwarded to RDS instance port 3306, 127.0.0.1 connection will work perfectly.

private final String dbUrl = “jdbc:mysql://127.0.0.1:3308”;

Reference:
https://aws.amazon.com/premiumsupport/knowledge-center/rds-connect-using-bastion-host-linux/

Leave a Reply

Your email address will not be published. Required fields are marked *