We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Connect to Your Database

Now that you have a database, we need our application server to connect to it. After all, they're in different subnets (public vs. private) in the same VPC. AWS adds a local route for your VPC CIDR by default, so subnets in that VPC can route to one another.

The key is security groups. Remember, security groups are like stateful firewalls that control traffic to and from your resources.

"Stateful" here just means we allow the return trip by default. If the firewall lets you out to https://www.boot.dev/, when that server responds to you it will also be allowed through the firewall.

Connection Path

Here's how traffic will flow from your application server to your database:

  1. Application server initiates connection
    • Your server needs an outbound rule allowing traffic to the database.
    • Port: 5432 (PostgreSQL default port)
    • If your server has a default outbound rule allowing all traffic, you won't need to add a specific rule here.
  2. Traffic routes through VPC
    • VPCs allow internal communication between subnets by default.
    • Your patientping-public-a subnet can reach your patientping-private-a subnet automatically.
  3. Database accepts connection
    • Your RDS instance needs an inbound rule allowing traffic from your application servers.
    • Port: 5432
    • Source: The security group of your application servers
    • Inbound connections, unlike outbound, must be managed carefully and only via specific rules.

Assignment

Configure security groups so your application server can reach the RDS instance on port 5432.

Cost check: No new billable resources in this lesson. You're only changing security group rules; your existing RDS instance (~$13/mo. for db.t3.micro) and EC2 instance costs are unchanged.

    1. psql -h patientping-db.XXXXX.us-east-1.rds.amazonaws.com -U postgres -d patientping
      

Run and submit the CLI tests.

Tip

For AWS CLI users, here's the syntax to configure security group rules:

# Add outbound rule to app server security group (assuming you want a specific rule)
aws ec2 authorize-security-group-egress --group-id APP-SG-ID --ip-permissions IpProtocol=tcp,FromPort=5432,ToPort=5432,UserIdGroupPairs=[{GroupId=RDS-SG-ID}]

# Add inbound rule to DB security group
aws ec2 authorize-security-group-ingress --group-id RDS-SG-ID --ip-permissions IpProtocol=tcp,FromPort=5432,ToPort=5432,UserIdGroupPairs=[{GroupId=APP-SG-ID}]