Search code examples
postgresqlamazon-web-servicesamazon-rdspsycopg2aws-security-group

Connect to AWS RDS database via psycopg2


I am trying to connect to my RDS database from my computer with a python script using psycopg2. python code:

import psycopg2
from db_credentials import *
import logging

def get_psql_conn():
    conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)
    logging.info("connected to DB!")
    return conn

I get the following error:

psycopg2.OperationalError: could not connect to server: Operation timed out
        Is the server running on host ********* and accepting
        TCP/IP connections on port 5432?

My security groups assigned to the RDS database:
SG 1: enter image description here

enter image description here


SG 2: enter image description here

enter image description here


Now i tried to make a security group which allows my computer IP to access the DB.
SG 3: enter image description here

enter image description here


I can connect to the DB from my ec2 instances, running the same python script as above. This seemingly has to do with the 2nd security group, as when i remove it, i can no longer connect from my ec2 instances either. It then throws the same error i get when trying to connect from my computer.


I have little understanding of RDS or security groups, i just followed internet tutorials, but seemingly couldnt make much sense out of it.


Any help is greatly appreciated! Thanks

Solution

  • When accessing an Amazon RDS database from the Internet, the database needs to be configured for Publicly Accessible = Yes.

    This will assign a Public IP address to the database instance. The DNS Name of the instance will also resolve to the public IP address.

    For good security on publicly-accessible databases, ensure that the Security Group only permits access from your personal IP address.