Select Language:
If you want your EC2 instances to access databases located in a different VPC, you’ll need to set up both network connections and security rules correctly. Here’s a simple guide to make this happen smoothly.
First, you have a few options for connecting the VPCs. You can use VPC peering, which creates a direct link between two VPCs. To do this, set up a peering connection and update both VPCs’ route tables so traffic can flow between their IP ranges. Keep in mind, VPC peering is a direct connection only between the two VPCs involved.
For more scalable and flexible options, consider using a Transit Gateway. It acts as a hub, connecting multiple VPCs easily, which is ideal if your setup involves several VPCs.
Another method is AWS PrivateLink, which allows your EC2 instances to access specific services securely without exposing the entire VPC. This involves setting up VPC endpoints for private access.
Once you’ve established network connectivity, you need to adjust the security groups to allow traffic. On the EC2 side, make sure the security group permits outbound connections to the database port—commonly 3306 for MySQL, 5432 for PostgreSQL, or 1433 for SQL Server. Point this outbound rule to the target VPC’s CIDR block or the security group attached to your database.
On the database side, the security group should accept inbound traffic on the same database port. You can specify the source as either the EC2 security group ID (if your setup supports cross-VPC security group referencing within the same region), the EC2 VPC’s CIDR block, or specific private IP addresses.
Remember that Network ACLs (Access Control Lists) in both VPCs might also need adjustments. Typically, these should allow outbound traffic from the source on your database port and ephemeral ports (1024-65535), and inbound traffic on the same ports on the target.
Here’s a quick example to clarify the setup:
– For the database security group, add an inbound rule allowing TCP traffic on port 5432 (for PostgreSQL) from your EC2’s CIDR or security group.
– For the EC2 security group, allow outbound TCP traffic on port 5432 to the database’s CIDR or security group.
Before proceeding, double-check that DNS resolution works properly if you’re using private DNS names. Confirm that your route tables are correctly set up with routes pointing to the other VPC. It’s also a good idea to test connectivity using tools like telnet or netcat from your EC2 instances to the database endpoint, ensuring everything is configured properly.
Finally, ensure your database is configured to accept connections from the EC2 VPC’s CIDR. With these steps, your EC2 instances should be able to access your databases across different VPCs securely and efficiently.




