connect AWS EC2 instance to RDS
To connect an Amazon Elastic Compute Cloud (EC2) instance to an Amazon Relational Database Service (RDS) instance, you’ll need to take the following steps:
- Ensure that the security group for your RDS instance allows inbound connections from the security group for your EC2 instance. You can do this by editing the inbound rules for your RDS security group and adding a rule that allows connections from the security group associated with your EC2 instance.
- Once the inbound rule is set, you can then connect to the RDS instance using the hostname and port number for the RDS instance, along with the username and password for your RDS database. For example, you can use the command line client, MySQL or PostgreSQL, to connect to your RDS instance.
mysql -h <RDS endpoint> -P <port> -u <username> -p
- Now you will be prompted for the password, give the password and you will be connected to your RDS instance.
- You can check if the ec2 instance and RDS instance are in the same VPC. if they are in different VPC, then you may have to set up a VPC peering connection and also make sure that the security groups are configured correctly to allow connections.
- If you’re using a language-specific library to connect to your RDS instance, such as the MySQL or PostgreSQL library for Python, you’ll need to install it on your EC2 instance, and use it to connect to your RDS instance.
- It’s a good practice to use the
IAMroles for the authentication for EC2 instance, this will remove the need of managing the authentication and access keys.
- Please Note that if the RDS instance is in a private subnet and not reachable over the internet and your EC2 instance is in a public subnet, you will need a NAT gateway or VPN connection to allow your EC2 instance to connect to the RDS instance.