Connect to your RDS instance from another VPC
Suppose you have created a PostgreSQL database without public accessibility (we are talking about AWS RDS right now) within some VPC (e.g.
VPC B) and you have a regular EC2 instance in another VPC (e.g.
VPC A). Now you want to connect a client (e.g. psql) from an instance to database. VPC peering is a tool that you need to use in such a case
Check different scenarios here if you want to connect from different VPC or without it altogether.
First of all you need to have a peering connection in place. Go to
Peering Connections and create new connection. Select requester (
VPC B) and accepter (
VPC B) and click Create. Then choose
Accept Request to activate created connection.
Subnets and check the subnet where you EC2 instance is launched. It should have route table associated with it.
Click on the target route table and choose
For the first VPC enter CIDR block of second VPC as a Destination and our Target is the peered connection we have already created. Do the same for the route tables of the second VPC. Now you have established routes between both of your VPCs.
You might have multiple subnets within the same VPC, so make sure to update all of them. Keep in mind that we are allowing resources to be accessed for the entire CIDR block because it’s just a bit easier to setup but you can limit that to particular subnet/resources (check links in resources below) if you need to.
Last thing is to actually allow incoming connections from your instance to a port database is listening on (in our case it’s
5432). Go to
Databases and click on your target database
Then select security group used and add a private IP address of your instance to the inbound rules like this
Now you should be able to test connectivity to your database from an instance. Connect to it first
$ ssh ec2-user@<public-ip> -i ~/.ssh/your-key.pem
and use either a netcat utility to check if the connection is possible
$ nc -v mydb.abczdrihzcxr.us-east-1.rds.amazonaws.com 5432
or a regular client
$ psql postgres://user:email@example.com:5432/database
That’s it, database is available and ready to be used from an instance.