Psycopg2 on AWS Lambda not connecting to RDS database
When I try to connect to my RDS Postgresql DB I get the following output
{
"errorMessage": "2022-01-07T13:28:35.428Z 975a92cd-936c-4d1c-8c23-6318cd609bff Task timed out after 10.01 seconds"
}
The DB is set to public access
Lambda psycopg2 connection code
connection = psycopg2.connect(user=user,
password=password,
host=host,
port=port,
database=database)
print(connection)
<connection object at 0x7ff7eb854b90; dsn: 'user=db_user password=db_password dbname=db_name host=rds_host port=5432', closed: 0>
RDS_LAMBDA_SECURITY_GROUP Inbound
Also all the subnets are associated to the route table
VPC Logs
Lots of REJECTED connections, not sure if it is safe to post a print here. Sometimes the connection to the DB is status ACCEPTED but there are a few other with REJECTED status
Any idea on why I still can't connect to my DB?
You mention that "the DB is set to public access". This means that the DNS Name of the database will resolve to a public IP address. Unfortunately, this means that the traffic will need to go out of the VPC and then back in again. It also means that the security groups cannot refer to each other, since this only permits access via private IP address.
For good security, you should not configure the database for 'public access'. The Lambda function will then resolve the database DNS Name to a private IP address, which should allow the connection.
So, you really have two options:
- Public database, Lambda function not connected to the VPC, security group permits access from entire Internet, or
- Private database, Lambda function connected to private subnet(s) of the same VPC as the RDS database, security group permits access from Lambda function's security group
Does your Lambda security group have an egress rule for port 5432? Can you post your Lambda code? It's not clear to me where "errorMessage" and its contents are coming from.
Relevant questions
RDS Postgresql migrate to Aurora Postgresql. Not showing "Aurora read replica" & "Migrate snapshot" options.
Accepted Answerasked 5 months agoPsycopg2 on AWS Lambda not connecting to RDS database
asked 5 months agoError connecting to Aurora PostgreSQL dB in .NET Core Lambda function.
asked 3 months agoRDS Database Instance does not show up in dropdown when creating RDS Proxy
asked 3 months agoWhy can't I find my RDS database from my lambda function?
asked 2 months agoHandler error when connecting lambda function to RDS database
asked 2 months agoAWS Lambda not able to connect to public RDS instance
asked a month agoUnable to connect to RDS database
asked a year agoMove RDS postgresql database to Aurora Serverless
Accepted Answerasked 3 years agoRDS does not support creating a DB instance
asked 3 months ago