James
James

Reputation: 367

Cannot connect my EC2 instance to private RDS for my Flask app

I have a flask app which I am trying to deploy to AWS using ECS with EC2 and a postgres RDS as my database.

My EC2 instance is in a public subnet, and my RDS instance is in a private subnet. Both on the same VPC.

I am successfully able to connect to the RDS instance from my local machine by using an ssh tunnel into my EC2 instance and using it as a bastion host. I have tested this with both pgadmin and a custom cli I have created in my flask app. When doing this - I created my database.

I can run my ECS task and use my app on my EC2's public DNS. However if I try to use functionality that uses my Flask-SQLAlchemy ORM (e.g. submitting a form to the db) I get the following error:

sqlalchemy.exc.InterfaceError: (pg8000.exceptions.InterfaceError) Can't create a connection to host

My database URI that I use when initialising my app is as follows:

db_uri = 'postgres+pg8000://username:password@host:5432/db'

Where username is the "Master Username" in the AWS RDS console, host is the "Endpoint" in the AWS RDS console, and db refers to the database name I created when connecting locally via ssh.

I have one security group for my EC2 and one security group for my RDS. Both are under the same VPC. I have configured an inbound rule on the RDS sg to allow TPC traffic from my EC2's private ipv4 address on port 5432.

I've tried modifying both the db_uri and playing around with my sg rules but no luck as of yet. I'm assuming I don't need to ssh tunnel when running my app on ECS itself.

Upvotes: 0

Views: 1137

Answers (2)

James
James

Reputation: 367

Embarrassingly, it was my RDS endpoint (host) that ended up being wrong. It contained a typo in my config file.

""We don't make mistakes, just happy little accidents." - Bob Ross

Upvotes: 0

Jyothish
Jyothish

Reputation: 1133

  1. From the EC2, do a telnet to the RDS on port 5432. If telnet is working then its evident that connection is available from EC2 to RDS.

    telnet rds_endpoint 5432

  2. If [1] is not working: Check the route table of public subnet and ensure that route is added for private subnet communication. Perform telnet again.

  3. If everything configured correctly in AWS side(SG, Route table..), then issue is related to sqlalchemy.

Upvotes: 1

Related Questions