How to connect to an RDS database from a local machine?

Got an RDS database in an AWS VPC?
Want to connect to it from your machine to debug a few things?

This guide will show you how to do it via an EC2 "bastion" instance and a SSH tunnel.

If you are looking for a simpler solution, check out the 7777 CLI.

Step 1: Launch an EC2 Bastion Host

  1. Login to the AWS Management Console.
  2. Navigate to the EC2 Dashboard and launch a new EC2 instance.
  3. Ensure the EC2 instance is in the same VPC as your private RDS instance.
  4. Select the subnet that has an internet gateway in its routing table. If you don't already have an internet gateway, then you can add it to the subnet after the EC2 instance is created.
  5. Associate an Elastic IP address to the EC2 instance for a static public IP ("Auto-assign public IP" needs to be enabled).
  6. Make sure the security group of the EC2 instance allows SSH access (port 22) to the EC2 instance from your local IP.
  7. Make sure the security group of the RDS database allows access (for example port 3306 for MySQL) from the EC2 IP address.

Step 2: Connect to the EC2 Bastion Host

  1. Open a terminal on your local machine.
  2. Use SSH to connect to the EC2 bastion host using the Elastic IP:
    ssh -i your-key.pem ec2-user@your-ec2-elastic-ip

Step 3: Configure SSH Tunneling

Now that you're connected to the bastion host, configure SSH tunneling to access the RDS instance:

  1. In the same terminal connected to the bastion host, run the following SSH command:
    ssh -L 3306:your-rds-endpoint:3306 -i your-key.pem ec2-user@your-ec2-elastic-ip -N

    Replace your-rds-endpoint with the endpoint of your RDS instance.

Step 4: Connect to the Private RDS DB Instance

With the SSH tunnel established, you can now connect to the private RDS DB instance from your local machine:

  1. Open your database client (e.g., MySQL Workbench, pgAdmin, etc.) on your local machine.
  2. Configure the database connection with the following details:
    • Host: 127.0.0.1
    • Port: 3306 (or the port of your RDS instance if different)
    • Username and Password: Your RDS database credentials
    • Database: Your database name
  3. Connect to the database.

Conclusion

You've successfully connected to your private Amazon RDS DB instance from your local machine using an Amazon EC2 instance as a bastion host.

Remember to terminate the SSH tunnel when you're finished to ensure security.

The easy alternative: use 7777

7777 is a CLI tool that automates the job of creating bastions servers, SSH keys, and SSH tunnels.

Because it creates temporary bastions using Fargate and SSH keys on the fly, it provides a simpler, cheaper, and more secure alternative to the manual process described above.

$ 7777
Tunnel created 🎉
Connect to MySQL on port 7777 on your machine:
mysql -h localhost -P 7777 -u admin -p
Hit Ctrl+C to stop the tunnel  
Learn more about 7777