We should learn about RDS to efficiently manage, automate, and scale production-grade relational databases without handling the underlying infrastructure.
β‘ Quick Reference
Keep the momentum going β everything you need on LearnXOps in one place:
- π Courses β Video courses & AI-built courses
- π Ebooks β Community ebooks & your own
- π§ͺ All Labs & Challenges β DevOps, Cloud, SRE & more
- βΈοΈ Kubernetes Labs & Playground β kind clusters, playground & challenges
- π€ AI Agent & Bot Labs β OpenClaw Β· Hermes Β· CrewAI Β· LangGraph Β· MCP
Learning points:
π‘ What is Amazon RDS, and why itβs used in cloud-native DevOps environments
π‘ Supported database engines: MySQL, PostgreSQL, MariaDB, SQL Server, Oracle, Aurora
π‘ Understanding RDS components: DB instance, subnet groups, parameter groups, option groups
π‘ RDS deployment types: Single-AZ vs Multi-AZ
π‘ Security best practices: VPC, subnet isolation, security groups, and IAM integration
π‘ Automatic backups, snapshots, and Point-in-Time Recovery
π‘ Monitoring and scaling RDS
π§ Learn here:
Official AWS Video on RDS

Amazon RDS - Relational Database Service
Amazon RDS (Relational Database Service) is a managed service provided by AWS that makes it easy to set up, operate, and scale a relational database in the cloud.
Key Features
- Fully Managed: AWS handles backups, patching, monitoring, and maintenance.
- Supports Multiple Engines:
- Amazon Aurora (MySQL/PostgreSQL-compatible)
- MySQL
- PostgreSQL
- MariaDB
- Oracle
- SQL Server
- Scalability: Easily scale compute and storage independently.
- High Availability: Multi-AZ deployments for automatic failover.
- Automated Backups: Point-in-time recovery.
- Security: Encryption at rest and in transit, IAM integration, VPC support.
π‘ Why Itβs Used in Cloud-Native DevOps
Amazon RDS is popular in DevOps environments due to its support for automation, scalability, high availability, and integration with AWS tools.
1. Automation-Friendly
- Supports Infrastructure as Code (Terraform, CloudFormation, AWS CDK).
- Integrates with CI/CD pipelines.
2. Managed Operations
- AWS handles patching, backups, and updates.
- Reduces operational overhead and human error.
3. On-Demand Scalability
- Auto-scaling storage.
- Scale read replicas easily.
4. High Availability & DR
- Multi-AZ deployments.
- Point-in-time recovery.
- Cross-region read replicas.
5. Security and Compliance
- VPC, IAM, KMS, CloudTrail integration.
- Encryption and compliance support (HIPAA, SOC 2).
6. Observability and Monitoring
- CloudWatch, Enhanced Monitoring, CloudWatch Database Insights (formerly Performance Insights).
π§ Supported Database Engines
| Engine | Description |
|---|---|
| MySQL | Popular open-source database for web apps. |
| PostgreSQL | Advanced open-source DB, great for complex queries. |
| MariaDB | MySQL fork with enhancements. |
| SQL Server | Microsoftβs enterprise-grade DB. |
| Oracle | Commercial DB for enterprise use. |
| Db2 | IBMβs enterprise database (on RDS since 2023). |
| Aurora | AWS-built engine compatible with MySQL and PostgreSQL; AWS quotes up to 5x the throughput of standard MySQL and 3x of PostgreSQL. |
π§© RDS Components
1. DB Instance
- Virtual DB environment (compute, storage, network)
- Example:
db.t3.medium, 100 GB PostgreSQL
2. DB Subnet Group
- Group of subnets across AZs.
- Required for RDS in VPC.
3. DB Parameter Group
- Configuration set for DB engine.
- Customizes buffer sizes, logging, etc.
4. DB Option Group
- Add advanced engine-specific features.
- E.g., Oracle Data Guard, SQL Server SQL Agent.
βοΈ RDS Deployment Types
Single-AZ Deployment
- Runs in one AZ.
- Use Cases: Dev/Test, cost-sensitive apps.
Multi-AZ Deployment
- Synchronous replication to standby in another AZ.
- Use Cases: Production, critical systems.
| Feature | Single-AZ | Multi-AZ |
|---|---|---|
| Availability | Low | High (Auto Failover) |
| Cost | Lower | Higher |
| Replication | None | Synchronous |
| Failover | Manual | Automatic |
| Backups | On primary | On standby |
| Best For | Dev/Test | Production |
π Security Best Practices
1. VPC
- Use private subnets.
- Avoid public access.
2. Subnet Isolation
- Separate app and DB tiers.
3. Security Groups
- Firewall rules for RDS.
- Allow only trusted IPs and required ports.
4. IAM Integration
- Avoid hardcoded credentials.
- Use IAM roles or Secrets Manager.
β Tips
- Enable encryption (KMS + SSL/TLS).
- Monitor failed logins.
- Use CloudTrail for auditing.
πΎ Backup & Recovery
1. Automatic Backups
- Entire DB instance backed up.
- Point-in-Time Recovery.
- Configurable retention (1-35 days).
2. Manual Snapshots
- User-initiated backups.
- Ideal before updates/migrations.
3. Point-in-Time Recovery (PITR)
- Restore to any second in backup window.
- Critical for data recovery scenarios.
π Monitoring RDS
CloudWatch Metrics
| Metric | Description |
|---|---|
| CPUUtilization | CPU usage % |
| FreeableMemory | Available memory |
| FreeStorageSpace | Remaining disk space |
| ReadIOPS / WriteIOPS | Disk I/O operations per second |
| DatabaseConnections | Number of active DB connections |
| ReplicaLag | Lag in seconds for read replicas |
Enhanced Monitoring
- OS-level metrics every 1β60 seconds.
- Deeper insights than CloudWatch.
Database Insights (formerly Performance Insights)
- Visualize DB load, slow queries and wait events. Since July 31, 2026 the Performance Insights console redirects to CloudWatch Database Insights (Standard mode is the free default; Advanced adds execution plans and fleet views).
- Supported: PostgreSQL, MySQL, Aurora, etc.
π Scaling RDS
1. Vertical Scaling
- Upgrade instance type (e.g.,
db.t3.mediumβdb.m5.large). - Causes a short outage while the instance is replaced; with Multi-AZ, RDS resizes the standby first and fails over, so downtime is about a minute.
2. Storage Scaling
- RDS storage autoscaling (set a maximum) works for every engine; Aurora storage grows automatically.
- You can also resize manually, but storage can only grow, never shrink.
3. Read Replicas
- Offload read traffic.
- MySQL, PostgreSQL, MariaDB, Oracle, SQL Server and Aurora.
- Can be promoted to standalone DB.
β Best Practices Summary
- Use Multi-AZ for production.
- Automate via Terraform/CloudFormation.
- Monitor via CloudWatch & Database Insights.
- Use IAM roles, Secrets Manager, and private VPC subnets.
- Enable encryption and PITR.
- Test restore and scaling regularly.
π§ Tip: Combine RDS with other AWS services like Lambda, ECS, or EKS for modern cloud-native app stacks.
ποΈ Additional Resources:
π What is Amazon RDS? β AWS Docs
π Amazon RDS Pricing
π Launch RDS using AWS Console
π Connect to RDS from EC2
π Backup & Restore in RDS
π CloudWatch for RDS Monitoring
π₯ Challenges
πΉ Challenge 1: Create a MySQL or PostgreSQL RDS instance using the AWS Console
πΉ Challenge 2: Connect to the RDS instance using DBeaver, MySQL CLI, or psql (based on what DB you have selected)
πΉ Challenge 3: Create a sample table, insert some records, and query them
πΉ Challenge 4: Enable automated backups and take a manual snapshot
πΉ Challenge 5: Create a read-only IAM user with access to RDS monitoring only
πΉ Challenge 6: Launch RDS in a private subnet and connect using a Bastion Host
πΉ Challenge 7: Configure an RDS parameter group to change a DB setting (e.g., max_connections)
πΉ Challenge 8: Set up CloudWatch Alarms for high CPU or storage usage
πΉ Challenge 9: Use RDS Snapshot Restore to clone your DB into a new instance
πΉ Challenge 10: Use AWS CLI to automate RDS snapshot creation
Scenario-based:
πΉ Challenge 11: Host a Python app in EC2 with DB (MySQL) in RDS
π‘ Step 1: Deploy a simple Flask or Node.js app on EC2
π‘ Step 2: Store app data (users, posts, etc.) in your Amazon RDS database
π‘ Step 3: Configure CloudWatch Alarms for database health
π‘ Step 4: Schedule a snapshot and demonstrate recovery
π‘ Step 5: Document and push your setup to GitHub
β Solutions
πΉ Challenge 1: Create a MySQL or PostgreSQL RDS Instance Using the AWS Console
Step 1: Go to the RDS Console
Step 2: Click on βCreate Databaseβ
- Choose a database creation method:
- β Select Standard create
Step 3: Engine Options
- Engine type: Choose MySQL or PostgreSQL
- Version: Select a supported major version (e.g., MySQL 8.4 or PostgreSQL 17); RDS MySQL 8.0 left standard support on July 31, 2026
Step 4: Templates
- Choose:
- β Free tier (if eligible) OR
- Production / Dev/Test
Step 5: Settings
- DB instance identifier:
my-rds-instance - Master username:
admin - Password: Create & confirm a strong password
Step 6: Instance Configuration
- DB instance class:
- Free tier:
db.t3.micro - Production: Choose based on CPU/RAM requirements
- Free tier:
- Storage:
- Type: General Purpose (SSD)
- Allocated storage: e.g., 20 GB
- β Enable autoscaling if needed
Step 7: Connectivity
- VPC: Choose your default/custom VPC
- Subnet group: Choose default (or custom)
- Public access:
- β Yes β if you want to connect from your laptop
- β No β for internal-only access (e.g., from EC2)
- VPC security group:
- Choose existing or create new
- Ensure port 3306 (MySQL) or 5432 (PostgreSQL) is open to your IP or app server
Step 8: Database Authentication
- Keep default as Password authentication
- (Optionally add IAM authentication later)
Step 9: Additional Config (Optional)
- Enable automated backups
- Enable Database Insights
- Enable deletion protection (for production environments)
Step 10: Click βCreate Databaseβ
- It will take 5β10 mins to provision the database
Step 11: Connect to the RDS Instance
- Once status is Available:
- Endpoint: Copy the DB endpoint
- Port: 3306 (MySQL) or 5432 (PostgreSQL)
- Use a CLI or tool like
mysql,psql, DBeaver, or MySQL Workbench to connect
β
Challenge 2: Connect to the RDS instance using DBeaver, MySQL CLI, or psql
πΈ MySQL:
mysql -h <endpoint> -P 3306 -u admin -p
πΈ PostgreSQL:
psql -h <endpoint> -p 5432 -U admin -d postgres
β Challenge 3: Create a sample table, insert some records, and query them
If you have selected MySQL:
πΈ Method: MySQL CLI
Step 1: Connect to the DB
mysql -h <RDS-ENDPOINT> -P 3306 -u admin -p
Enter the password when prompted.
Step 2: Create a Database
CREATE DATABASE testdb;
USE testdb;
Step 3: Create Table
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
Step 4: Insert Sample Records
INSERT INTO users (name, email)
VALUES
('Alice', '[email protected]'),
('Bob', '[email protected]'),
('Charlie', '[email protected]');
Step 5: Query the Data
SELECT * FROM users;
Output:
+----+---------+---------------------+
| id | name | email |
+----+---------+---------------------+
| 1 | Alice | [email protected] |
| 2 | Bob | [email protected] |
| 3 | Charlie | [email protected] |
+----+---------+---------------------+
If you have selected PostgreSQL:
πΈ Method: psql CLI
Step 1: Connect to the DB
psql -h <RDS-ENDPOINT> -U admin -d postgres -p 5432
Enter the password when prompted.
Step 2: Create a Database (Optional)
CREATE DATABASE testdb;
\c testdb
Step 3: Create Table
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
Step 4: Insert Sample Records
INSERT INTO users (name, email)
VALUES
('Alice', '[email protected]'),
('Bob', '[email protected]'),
('Charlie', '[email protected]');
Step 5: Query the Table
SELECT * FROM users;
Challenge 4: Enable Automated Backups and Take a Manual Snapshot
Step 1: Enable Automated Backups
- Go to RDS Console β Databases
- Select your RDS instance
- Click Modify
- Scroll to Backup section:
- Enable automated backups: β Yes
- Backup retention period: e.g., 7 days
- Preferred backup window: (optional) choose a low-traffic time
- Click Continue β Apply Immediately
β RDS will now create daily backups automatically.
Step 2: Create a Manual Snapshot
- Go to RDS Console β Databases
- Select your DB instance β Actions β Take snapshot
- Enter a Snapshot name: e.g., manual-snapshot-preupgrade
- Click Take Snapshot
- β³ Wait for the snapshot status to become available
Step 3: View Snapshots
- Go to Snapshots β Manual (for user-created)
- Go to Snapshots β Automated (for AWS-managed backups)
You can:
- Restore to a new instance
- Share snapshot with another AWS account
- Export snapshot to S3 (Aurora & supported engines)
Challenge 5: Create a Read-Only IAM User with Access to RDS Monitoring Only
Using AWS Console
Step 1: Create IAM User
- Go to IAM Console β Users β Add users
- User name:
rds-monitor-user - Access type:
- β Console access (for dashboard view) OR
- β Programmatic access (CLI/SDKs)
- Set password or generate access keys
- Click Next: Permissions
Step 2: Attach Permissions
- Click Create policy β Go to JSON tab
- Paste the following JSON:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"rds:Describe*",
"cloudwatch:GetMetricData",
"cloudwatch:GetMetricStatistics",
"cloudwatch:ListMetrics"
],
"Resource": "*"
}
]
}
- Name the policy:
RDSMonitoringReadOnly - Create and attach this policy to
rds-monitor-user
Step 3: Finish & Verify Access
- Youβll receive the login URL and credentials
- Login via AWS Console and verify:
- β Can view RDS instances
- β Can see metrics in CloudWatch
- β Cannot delete/modify anything
Using AWS CLI
Step 1: Create IAM User
aws iam create-user --user-name rds-monitor-user
Step 2: Create Custom Policy
- Create a file
rds-monitor-policy.json:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"rds:Describe*",
"cloudwatch:GetMetricData",
"cloudwatch:GetMetricStatistics",
"cloudwatch:ListMetrics"
],
"Resource": "*"
}
]
}
- Create the policy:
aws iam create-policy \
--policy-name RDSMonitoringReadOnly \
--policy-document file://rds-monitor-policy.json
Step 3: Attach Policy to User
aws iam attach-user-policy \
--user-name rds-monitor-user \
--policy-arn arn:aws:iam::<your-account-id>:policy/RDSMonitoringReadOnly
β Your IAM user now has read-only access to RDS and related CloudWatch metrics.
β
Challenge 6: Launch RDS in a Private Subnet and Connect Using a Bastion Host
Step 1: Set Up the VPC & Subnets (If Not Already Done)
| Subnet Type | Contains | Public IP |
|---|---|---|
| Public Subnet | Bastion EC2 | Yes |
| Private Subnet | RDS Instance | No |
Ensure:
- NAT Gateway exists for private subnet (for RDS upgrades/patches).
- Internet Gateway exists and routes from public subnet.
Step 2: Launch RDS in Private Subnet
- Go to RDS Console β Create database
- Choose engine: β MySQL / PostgreSQL
- Select Standard create
- Select VPC and choose subnet group with private subnets
- Public access: β No
- VPC security group:
- Create or use one that allows port 3306 (MySQL) or 5432 (PostgreSQL) from Bastion EC2's SG
- Complete DB creation
- β Your RDS now only has a private IP
Step 3: Launch Bastion EC2 in Public Subnet
- Launch EC2 instance in the public subnet of the same VPC
- Select Amazon Linux / Ubuntu
- Enable Auto-assign public IP: β Yes
- Attach a security group that:
- Allows SSH from your IP (port 22)
- Allows egress to private subnet
- Save key pair (e.g.,
bastion.pem)
Step 4: Security Group Setup
| Security Group | Inbound Rules |
|---|---|
| Bastion SG | SSH (22) from your IP |
| RDS SG | DB port (3306/5432) from Bastion SG only |
Step 5: Connect from Local Machine to RDS via Bastion
Option 1: SSH into Bastion, then connect to DB
ssh -i bastion.pem ec2-user@<Bastion-Public-IP>
# Then connect to RDS:
# MySQL
mysql -h <RDS-private-endpoint> -u admin -p
# PostgreSQL
psql -h <RDS-private-endpoint> -U admin -d postgres
Option 2: Use SSH Tunnel from Local Machine
ssh -i bastion.pem -L 3307:<RDS-Private-Endpoint>:3306 ec2-user@<Bastion-Public-IP>
# Then connect locally
mysql -h 127.0.0.1 -P 3307 -u admin -p
β
Challenge 7: Configure RDS Parameter Group to Change a DB Setting (e.g., max_connections)
Step 1: Create a Custom Parameter Group
- Go to RDS Console β Parameter groups
- Click Create parameter group
- Parameter group family: e.g.,
mysql8.4,postgres17 - Type: DB Parameter Group
- Name:
custom-mysql-pg - Description: Increase max_connections
- Click Create
Step 2: Modify the Parameter
- Click on the new parameter group
- Search for
max_connections - Change value to (e.g.,
500) - Click Save changes
Step 3: Apply Parameter Group to RDS
- Go to RDS β Databases
- Select DB instance β Modify
- Under DB parameter group, choose
custom-mysql-pg - Click Continue β Apply Immediately
β οΈ Attaching a new parameter group always needs a reboot. After that, dynamic parameters (MySQLmax_connections) apply immediately, while static ones (PostgreSQLmax_connections) still need a reboot.
Step 4: Reboot the Instance
- Go to RDS instance β Actions β Reboot
Step 5: Verify the Change
MySQL:
SHOW VARIABLES LIKE 'max_connections';
PostgreSQL:
SHOW max_connections;
βοΈ AWS CLI Commands
Step 1: Create Parameter Group
aws rds create-db-parameter-group \
--db-parameter-group-name custom-mysql-pg \
--db-parameter-group-family mysql8.4 \
--description "Custom parameter group with higher max_connections"
Step 2: Modify Parameter
aws rds modify-db-parameter-group \
--db-parameter-group-name custom-mysql-pg \
--parameters "ParameterName=max_connections,ParameterValue=500,ApplyMethod=immediate"
Step 3: Attach to RDS Instance
aws rds modify-db-instance \
--db-instance-identifier my-rds-instance \
--db-parameter-group-name custom-mysql-pg \
--apply-immediately
Step 4: Reboot (If Required)
aws rds reboot-db-instance \
--db-instance-identifier my-rds-instance
The rest of the steps are the same.
πΉ Challenge 8: Set up CloudWatch Alarms for High CPU or Storage Usage
β Using AWS Console
Step 1: Go to CloudWatch β Alarms β Create Alarm
Step 2: Select Metric
- Browse: RDS β Per-Database Metrics β
[DBInstanceIdentifier] - Choose:
CPUUtilizationorFreeStorageSpace
Step 3: Set Conditions
For CPU:
- Threshold:
>= 80 - Period:
5 minutes - Evaluation:
2 out of 3
For Storage:
- Threshold:
<= 1000000000(1 GB) - Period:
5 minutes
Step 4: Notifications
- Choose or create an SNS topic
- Add your email and confirm the subscription
Step 5: Name & Create
- Name:
HighCPU-RDS,LowStorage-RDS - Click Create alarm
β Using AWS CLI
Step 1: Create SNS Topic & Subscribe (if not already done)
aws sns create-topic --name RDSAlerts
aws sns subscribe \
--topic-arn arn:aws:sns:<region>:<account-id>:RDSAlerts \
--protocol email \
--notification-endpoint [email protected]
Step 2: Create High CPU Alarm
aws cloudwatch put-metric-alarm \
--alarm-name HighCPU-RDS \
--metric-name CPUUtilization \
--namespace AWS/RDS \
--statistic Average \
--period 300 \
--threshold 80 \
--comparison-operator GreaterThanOrEqualToThreshold \
--evaluation-periods 2 \
--alarm-actions arn:aws:sns:<region>:<account-id>:RDSAlerts \
--dimensions Name=DBInstanceIdentifier,Value=my-rds-instance \
--unit Percent
Step 3: Create Low Storage Alarm
aws cloudwatch put-metric-alarm \
--alarm-name LowStorage-RDS \
--metric-name FreeStorageSpace \
--namespace AWS/RDS \
--statistic Average \
--period 300 \
--threshold 1000000000 \
--comparison-operator LessThanOrEqualToThreshold \
--evaluation-periods 2 \
--alarm-actions arn:aws:sns:<region>:<account-id>:RDSAlerts \
--dimensions Name=DBInstanceIdentifier,Value=my-rds-instance \
--unit Bytes
β
Challenge 9: Use RDS Snapshot Restore to Clone Your DB into a New Instance
Using AWS Console
Step 1: Go to RDS Console β Snapshots
- Select a manual or automated snapshot
- Click Actions β Restore Snapshot
Step 2: Configure the New DB Instance
- DB instance identifier:
clone-mydb - DB instance class: e.g.,
db.t3.medium - Storage: Increase size if needed
- Subnet group: Choose one in the same VPC
- Public access:
- β No (for staging/test)
- β Yes (for external testing)
- Security group: Allow DB port access from your IP or Bastion
Step 3: Restore
- Click Restore DB instance
- Wait until status becomes
Available
Step 4: Connect to the New DB
- Use the new endpoint in tools like
psql,mysql, or your app
mysql -h clone-mydb.<xyz>.rds.amazonaws.com -u admin -p
Using AWS CLI:
Step 1: List Available Snapshots
aws rds describe-db-snapshots \
--db-instance-identifier my-rds-instance
- Note the
DBSnapshotIdentifier, e.g.,manual-snapshot-preupgrade
Step 2: Restore Snapshot to New Instance
aws rds restore-db-instance-from-db-snapshot \
--db-instance-identifier clone-mydb \
--db-snapshot-identifier manual-snapshot-preupgrade # manual IDs have no "rds:" prefix (automated ones do) \
--db-instance-class db.t3.medium \
--no-publicly-accessible
Step 3: Wait and Connect
aws rds describe-db-instances \
--db-instance-identifier clone-mydb \
--query "DBInstances[0].Endpoint.Address"
β Challenge 10: Automate RDS Snapshot Creation Using AWS CLI
Step 1: Create a Manual Snapshot via CLI
aws rds create-db-snapshot \
--db-instance-identifier my-rds-instance \
--db-snapshot-identifier my-rds-snapshot-$(date +%Y%m%d-%H%M%S)
This will create a snapshot named like: my-rds-snapshot-20250326-143500
Step 2: Verify the Snapshot
aws rds describe-db-snapshots \
--db-instance-identifier my-rds-instance \
--snapshot-type manual \
--query "DBSnapshots[*].{ID:DBSnapshotIdentifier,Status:Status}" \
--output table
β Challenge 11: Host a Python App in EC2 with DB (MySQL) in RDS
π‘ Step 1: Deploy a Simple Flask App on EC2
Launch EC2 Instance:
- OS: Amazon Linux 2023 / Ubuntu (Amazon Linux 2 reached end of support on June 30, 2026)
- Type:
t3.micro(Free Tier) - Security Group:
- Allow SSH (22) from your IP
- Allow the app port (8080) from anywhere
Install Python & Flask:
# Amazon Linux 2023
sudo dnf install -y python3 python3-pip git
# Ubuntu: sudo apt update && sudo apt install -y python3-venv git
# A virtualenv avoids "externally-managed-environment" errors on newer distros
python3 -m venv ~/venv && source ~/venv/bin/activate
pip install flask pymysql
Sample Flask App (app.py)
from flask import Flask
import pymysql
import os
app = Flask(__name__)
RDS_HOST = os.environ.get('RDS_HOST', 'your-rds-endpoint.rds.amazonaws.com')
RDS_USER = os.environ.get('RDS_USER', 'admin')
RDS_PASSWORD = os.environ.get('RDS_PASSWORD', 'yourpassword')
RDS_DB = os.environ.get('RDS_DB', 'mydb')
try:
db = pymysql.connect(
host=RDS_HOST,
user=RDS_USER,
password=RDS_PASSWORD,
database=RDS_DB,
connect_timeout=5
)
print("β
Connected to RDS MySQL successfully.")
except Exception as e:
print("β Failed to connect to RDS MySQL:", e)
exit()
@app.route('/')
def index():
return "π Flask App is running and connected to RDS!"
@app.route('/add/<name>')
def add_user(name):
try:
db.ping(reconnect=True) # reopen if MySQL closed the idle connection
with db.cursor() as cursor:
cursor.execute("INSERT INTO visitors (name) VALUES (%s)", (name,))
db.commit()
return f"β
Added {name} to the database."
except Exception as e:
return f"β Failed to insert data: {e}"
@app.route('/users')
def list_users():
try:
db.ping(reconnect=True) # reopen if MySQL closed the idle connection
with db.cursor() as cursor:
cursor.execute("SELECT * FROM visitors")
users = cursor.fetchall()
return {"users": users}
except Exception as e:
return f"β Failed to fetch users: {e}"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080) # ports below 1024 need root
Set Environment Variables:
export RDS_HOST=my-rds-instance.abc123.us-east-1.rds.amazonaws.com
export RDS_USER=admin
export RDS_PASSWORD=yourpassword
export RDS_DB=mydb
π‘ Step 2: Store App Data in Amazon RDS (MySQL)
Launch RDS MySQL Instance:
- Engine: MySQL
- Instance:
db.t3.micro - Storage: 20 GB
- Public Access: β (or β with Bastion)
- Security Group: Allow port 3306 from EC2 SG
Create Database & Table:
CREATE DATABASE mydb;
USE mydb;
CREATE TABLE visitors (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);
π‘ Step 3: Configure CloudWatch Alarms for DB Health
Create Alarms via Console:
- Go to CloudWatch β Alarms β Create Alarm
- Metric: RDS β Per-Database Metrics β [your DB]
- CPUUtilization > 80%
- FreeStorageSpace < 1 GB
- Action: Create SNS topic β Add email β Confirm subscription
π‘ Step 4: Schedule Snapshot & Demonstrate Recovery
Manual Snapshot via CLI:
aws rds create-db-snapshot \
--db-instance-identifier my-rds-instance \
--db-snapshot-identifier snapshot-$(date +%Y%m%d-%H%M%S)
Automate with Cron:
crontab -e
Add:
0 3 * * * /home/ec2-user/snapshot.sh >> /home/ec2-user/rds-snapshot.log 2>&1
snapshot.sh Script:
#!/bin/bash
# chmod +x snapshot.sh; the EC2 role needs rds:CreateDBSnapshot
aws rds create-db-snapshot \
--db-instance-identifier my-rds-instance \
--db-snapshot-identifier snapshot-$(date +%Y%m%d-%H%M%S)
Restore Snapshot to New DB:
aws rds restore-db-instance-from-db-snapshot \
--db-instance-identifier my-rds-restore \
--db-snapshot-identifier snapshot-20250326-030000 \
--db-instance-class db.t3.micro
π‘ Step 5: Document & Push to GitHub
- Create a GitHub repository
- Add
app.py,README.md, andsnapshot.sh - Push your code using Git
git init
git add .
git commit -m "Initial Flask + RDS deployment"
git remote add origin <your-repo-url>
git push -u origin main
How to Participate?
β
Complete the tasks and challenges.
β
Document your progress and key takeaways on GitHub ReadMe, Medium, or Hashnode.
β
Share the above in a LinkedIn post tagging me (Sandip Das), and use #60DaysOfDevOps to engage with the community!
β‘ Quick Reference
Keep the momentum going β everything you need on LearnXOps in one place:
- π Courses β Video courses & AI-built courses
- π Ebooks β Community ebooks & your own
- π§ͺ All Labs & Challenges β DevOps, Cloud, SRE & more
- βΈοΈ Kubernetes Labs & Playground β kind clusters, playground & challenges
- π€ AI Agent & Bot Labs β OpenClaw Β· Hermes Β· CrewAI Β· LangGraph Β· MCP

Member discussion