Search code examples
amazon-web-servicesamazon-ec2amazon-rdsaws-security-group

Connect to AWS RDS database from EC2


I'm student and I start to explore AWS with free tier EC2 and RDS. I have a spring boot app and this is my application.properties

server.port=8080
spring.datasource.url=jdbc:mysql://tiktok.cdo6k4mey5el.us-east-1.rds.amazonaws.com:3306/tiktok
spring.datasource.username=admin
spring.datasource.password=**********
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

When running application on my local laptop, I can connect to the RDS database and can perform CRUD actions there! However, when I deploy my app to EC2, I can not connect to MySQL on RDS! These are my security groups for EC2 enter image description here enter image description here

An this is how I set the inbound with outbound on RDS

enter image description here enter image description here enter image description here

Could anyone have experience this before or found out what I did wrong to help me figure it out? Thank you!


Solution

  • The problem is related to your Inbound rules on the database, which are only accepting connections from your laptop and from the Database (yes, from itself!).

    The typical configuration is:

    • A Security Group on the EC2 instance (EC2-SG) that permits:
      • Inbound: SSH (port 22) from your laptop on the Internet
      • Outbound: All Traffic
    • A Security Group on the RDS instance (DB-SG) that permits:
      • Inbound: access on the database port from EC2-SG and also from your laptop
      • Outbound rules not required

    That is, DB-SG should specifically reference EC2-SG. This way, any EC2 instance that is assigned the EC2-SG security group will be permitted to access the database.

    If you are running a web application on the EC2 instance, then also add the necessary inbound ports (eg 80, 443).

    In general, try to avoid mentioning specific IP addresses in Security Groups unless it is for a resource on the Internet.

    In looking at your screenshots, I suspect that the Outbound rules on the EC2 instance (which are not shown) might be the problem. It should be allowing All Traffic outbound.