<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sankalparava on Medium]]></title>
        <description><![CDATA[Stories by Sankalparava on Medium]]></description>
        <link>https://medium.com/@sankalparava619?source=rss-d5b9d126ec67------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PKmPdhkZwGupaHCchZ8vPg.jpeg</url>
            <title>Stories by Sankalparava on Medium</title>
            <link>https://medium.com/@sankalparava619?source=rss-d5b9d126ec67------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 16:38:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sankalparava619/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I Built a Production-Style AWS Infrastructure With Terraform Here’s What Actually Happened]]></title>
            <link>https://medium.com/@sankalparava619/i-built-a-production-style-aws-infrastructure-with-terraform-heres-what-actually-happened-2f1a8fc8e283?source=rss-d5b9d126ec67------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f1a8fc8e283</guid>
            <category><![CDATA[aws-vpc]]></category>
            <category><![CDATA[terraform-cloud]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[aws-rds]]></category>
            <dc:creator><![CDATA[Sankalparava]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 06:33:58 GMT</pubDate>
            <atom:updated>2026-07-21T06:33:58.096Z</atom:updated>
            <content:encoded><![CDATA[<pre>A few weeks ago I decided I was done clicking around the AWS Console to build infrastructure. If I wanted to call myself a Cloud Engineer, my infrastructure needed to live in code — versioned, repeatable, and something I could tear down and rebuild in minutes instead of hours.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jz9EO6iMAZKq0JdSEFAxEA.png" /></figure><p><strong>The complete infrastructure flow — Developer pushes code to GitHub, Terraform triggers and provisions the entire AWS environment, state stored remotely in S3. Inside the VPC: Users hit the ALB over HTTPS, traffic routes to EC2 with Auto Scaling, EC2 connects to RDS PostgreSQL on port 5432 in a private subnet. Security groups enforce strict access — ALB is public, EC2 accepts only ALB traffic, RDS accepts only EC2 traffic</strong></p><p>So I picked a real-ish project: <strong>food-app</strong>, a three-tier setup with a VPC, an Application Load Balancer, an EC2-hosted Node.js backend, and a private PostgreSQL database on RDS. Nothing exotic. But building it entirely with Terraform — end to end, including the two mistakes I made along the way — taught me more than any tutorial had.</p><p>This is that journey, screenshot by screenshot.</p><h3>1. Laying the Foundation</h3><p>Every Terraform project starts the same way — you tell it what providers you need and where to store state.</p><p><strong>terraform init</strong></p><p>This pulls down the AWS provider and connects to my S3 backend for remote state storage. No local terraform.tfstate files floating around waiting to get lost or overwritten.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*iCtomEqRdzNYUJ0H3KlFig.png" /><figcaption><strong>terraform init — Initializes Terraform, downloads AWS provider, connects to S3 backend for remote state storage.</strong></figcaption></figure><p>A few seconds later, confirmation: hashicorp/aws v6.49.0 installed, and a .terraform.lock.hcl file generated to lock that provider version in place. Small detail, but it’s the difference between “works on my machine” and actually reproducible infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*GjCnzT47jYismnv2ZUFz8g.png" /><figcaption><strong>terraform init — Confirms </strong><strong>hashicorp/aws v6.49.0 installed, and </strong><strong>.terraform.lock.hcl created — this locks the provider version so the same setup is reproducible every time.</strong></figcaption></figure><p>To sanity-check that Terraform wasn’t lying to me, I jumped into the AWS Console. And there it was — food-app-dev-vpc, fully wired up: 4 subnets spread across 2 availability zones, 3 route tables, an Internet Gateway, and a NAT Gateway. All of it created from a module I wrote once and can reuse for every environment going forward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EkAVXMaRtpMGu_p-gYPiTw.png" /><figcaption><strong>Proof that the VPC module worked — shows </strong><strong>food-app-dev-vpc with 4 subnets across 2 AZs, 3 route tables, an Internet Gateway, and a NAT Gateway, all created from code.</strong></figcaption></figure><h3>2. Locking Down the Network Before Anything Else</h3><p>I’m a firm believer that security groups should be designed <em>before</em> you provision compute, not bolted on afterward. So the next few terraform plan runs were all about access control.</p><p>First, the ALB security group — the only thing in this whole stack allowed to talk to the public internet:</p><p><strong>terraform plan</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*0H9Wh9rozD1GJkpCWP0upA.png" /><figcaption><strong>terraform plan </strong>- <strong>Previews the ALB security group,the only thing in the whole stack allowed to accept public HTTP/HTTPS traffic.</strong></figcaption></figure><p>Then both security groups together, so I could see the relationship in one plan output: food-app-dev-alb-sg and food-app-dev-ec2-sg. The EC2 security group only accepts traffic <em>from</em> the ALB — never directly from the internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*OEveIm7-4zNUghG2n1ouTQ.png" /><figcaption><strong>terraform plan </strong>- <strong>Shows </strong><strong>food-app-dev-alb-sg and </strong><strong>food-app-dev-ec2-sg together — EC2 only accepts traffic from the ALB, never directly from the internet.</strong></figcaption></figure><p>And then the one I care about most — the RDS security group. Port 5432, ingress restricted with a description that literally says “PostgreSQL from EC2 only.” The database has zero path to the public internet. Not “hard to reach.” Actually unreachable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*tmJOaL_bE0X1IAT0HUKiEA.png" /><figcaption><strong>Terraform Plan </strong>- <strong>RDS security group planned — port 5432, ingress restricted to “PostgreSQL from EC2 only.” The database has zero path to the public internet.</strong></figcaption></figure><p>Plan looked clean, so I applied it.</p><p><strong>terraform apply</strong></p><p>All three security groups created in under 10 seconds. Apply complete! Resources: 3 added, 0 changed, 0 destroyed. That line never gets old.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*sJpB3aiEo0Qs6LTFgET-mA.png" /><figcaption><strong>terrafrom apply — All 3 security groups created in under 10 seconds — </strong><strong>Apply complete! Resources: 3 added, 0 changed, 0 destroyed.</strong></figcaption></figure><h3>3. Standing Up the Database</h3><p>With the network boundaries in place, it was time for the database itself.</p><p>terraform plan</p><p>The plan laid out the full RDS configuration: PostgreSQL 16.3, db.t3.micro, 20GB storage, database name foodappdb, placed inside a private subnet group. Nothing about this instance is internet-facing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*WRoYGFpTin5dU-hOnb5Sow.png" /><figcaption><strong>terraform plan<br> Previews the full RDS setup — Postgres 16.3, </strong><strong>db.t3.micro, 20GB storage, </strong><strong>db_name=foodappdb, placed in a private subnet group</strong>.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*WRoYGFpTin5dU-hOnb5Sow.png" /><figcaption><strong>terraform plan<br> Shows </strong><strong>username=foodappuser, </strong><strong>storage_type=gp2, and the subnet group name — all defined in code, no manual console input.</strong></figcaption></figure><p>One detail I actually appreciated seeing in the plan output: the DB subnet group spanning both private subnets across two AZs. That’s not something I configured manually — Terraform handled the subnet placement automatically based on the module, which means this database has no single point of failure by design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*4ywAFiHNZMfAqqzv5xXGnA.png" /><figcaption><strong>terraform plan<br> The DB subnet group spans both private subnets across 2 AZs — Terraform handles subnet placement automatically, so RDS has no single point of failure.</strong></figcaption></figure><p>Then came the part that tests your patience: terraform apply, and watching RDS provision. Terraform doesn’t just fire the API call and walk away — it waits, polling every 10 seconds, until the instance is actually ready. Total time: 4 minutes 45 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*bvn07Vo0VGLIFSzxJEus8Q.png" /><figcaption><strong>terraform apply<br> RDS provisioning takes time. Terraform waits and polls every 10 seconds until it&#39;s actually ready — </strong><strong>Apply complete! Resources: 1 added.</strong></figcaption></figure><p>Apply complete! Resources: 1 added. Over to the console to confirm — food-app-dev-db, status <strong>available</strong>, db.t3.micro, running in ap-south-1b, internet access disabled. A genuinely private database, built entirely from code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u0mWT2JCeHOFXyjw6ETEYw.png" /><figcaption><strong>Proof the database exists correctly — </strong><strong>food-app-dev-db available, </strong><strong>db.t3.micro, PostgreSQL, </strong><strong>ap-south-1b, internet access disabled. Fully private</strong></figcaption></figure><h3>4. The First Mistake (and the Fix)</h3><p>Here’s where the story gets honest. I’d fat-fingered a couple of values in the RDS module and the tfvars file — nothing catastrophic, just not quite right. This is the part tutorials tend to skip, but it’s the part where Terraform actually proves its value.</p><p><strong>nano ~/food-app-infra/modules/rds/main.tf<br>nano ~/food-app-infra/environments/dev/terraform.tfvars</strong></p><p><strong>terraform apply</strong></p><p>I fixed the config, reapplied, and Terraform only touched the difference. No full teardown, no rebuild from scratch — just a targeted update to the exact resource that changed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*jWvKd1KJAYIzUx9HLzTX7Q.png" /><figcaption><strong>Fixed an RDS config mistake — edited the module and tfvars, then reapplied. Terraform only changes the difference, not a full rebuild.</strong></figcaption></figure><p>Fixed an RDS config mistake — edited the module and tfvars, then reapplied. Terraform only changes the difference, not a full rebuild.</p><p>The second mistake was smaller but sneakier — I’d set instance_type = “t2.micro” in my tfvars, which isn’t the right free-tier type for ap-south-1. Caught it with a quick grep:</p><p><strong>grep instance_type ~/food-app-infra/environments/dev/terraform.tfvars</strong></p><p><strong># Output: instance_type = “t3.micro”</strong></p><p><strong>terraform apply</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*xLZT_cqdojUPxC7jO2Ct7w.png" /><figcaption><strong>Caught the wrong instance type — </strong><strong>t2.micro corrected to </strong><strong>t3.micro (the actual free-tier type for </strong><strong>ap-south-1). One line fix, one apply.</strong></figcaption></figure><p>One line changed, one apply, done. This is the entire pitch for Infrastructure as Code in a nutshell: mistakes become one-line diffs instead of afternoon-long incident reviews.</p><h3>5. Bringing the Compute Layer Online</h3><p>With the network and database solid, it was time to launch the actual application server.</p><p><strong>terraform plan</strong></p><p>The launch template came together first — ami-0f58b397bc5c1f2e8, t3.micro, keyed with food-app-dev-key, and a user data script attached (marked as a sensitive value in the plan output, so it doesn’t leak into logs).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*xdToefhY9uIZxGyH5FnuXA.png" /><figcaption><strong>terraform plan<br> Launch template planned — AMI, </strong><strong>t3.micro, </strong><strong>key_name=food-app-dev-key, and the user data script attached as a sensitive value (so it doesn&#39;t leak into logs).</strong></figcaption></figure><p>Then the full EC2 instance configuration — every parameter visible in the plan before a single resource actually gets created. AMI, instance type, key pair, user data, all of it reviewable up front.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*6OdRXIYYVKejvBt3zfeZAQ.png" /><figcaption><strong>terraform plan<br> Every parameter of the EC2 instance previewed before creation — AMI, instance type, key pair, user data, all reviewable up front.</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*4Iy7UBbMuce5w-K921hOvA.png" /><figcaption><strong>terraform plan<br> EC2 tagged </strong><strong>food-app-dev-app-server and placed in the public subnet. Consistent tagging is what makes cost tracking usable across a real AWS account.</strong></figcaption></figure><p>The instance got tagged food-app-dev-app-server and placed in the correct public subnet. Small thing, but consistent tagging across every resource is what makes cost tracking in a real AWS account actually usable instead of a guessing game.</p><h3>6. The State Refresh Moment</h3><p>By this point I had 14 resources living in AWS — VPC, subnets, IGW, NAT, route tables, security groups, RDS, all of it. Before applying any further change, Terraform refreshes its understanding of everything that already exists.</p><p><strong>terraform apply</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*q_le6IGGKvYX8pVbaDmlGw.png" /><figcaption><strong>terraform apply<br> Terraform refreshes everything it already knows about before applying changes — VPC, subnets, IGW, NAT, route tables, all in sync.</strong></figcaption></figure><p>Only the actual delta gets touched. Everything else stays exactly as it is. This is the moment where Terraform stops feeling like a scripting tool and starts feeling like an actual source of truth for your infrastructure.</p><p>And then, the payoff:</p><p><strong>terraform plan</strong></p><p># No changes. Your infrastructure matches the configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*LtCTsbJmm4X7RXAXaKxfJQ.png" /><figcaption><strong>terraform apply<br> A refresh across every existing resource in the account — confirming Terraform&#39;s understanding of the infrastructure matches reality before touching anything.</strong></figcaption></figure><p>Code and reality, perfectly in sync. That single line is the entire promise of Infrastructure as Code.</p><h3>7. Getting the Keys to the Kingdom</h3><p><strong>terraform output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*DduUAuLKL7ZeSvITQ7BEQA.png" /><figcaption><strong>terraform output<br> Prints </strong><strong>alb_dns_name, </strong><strong>ec2_public_ip, and </strong><strong>rds_endpoint — everything needed to actually reach the app, in one command.</strong></figcaption></figure><p>The ALB DNS name, the EC2 public IP (13.207.194.246), and the RDS endpoint (food-app-dev-db.cj4aaqu0g707.ap-south-1.rds.amazonaws.com:5432) — everything needed to actually reach the application, printed in one command.</p><p>Back in the console, the instance itself: food-app-dev-app-server, t3.micro, 3/3 status checks passed, state Running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y7BoFwMoj7C5FfD-jzTFWg.png" /><figcaption><strong>food-app-dev-app-server, </strong><strong>t3.micro, 3/3 status checks passed, state Running — the instance is live and healthy.</strong></figcaption></figure><h3>8. Getting the Application Actually Running</h3><p>Infrastructure was live. Now the app needed to run on it.</p><p>pm2 start src/index.js — name food-app</p><p>pm2 save</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*GXAFHbOqQYoz60637-PfYw.png" /><figcaption><strong>Starts the Node.js backend and saves the process list so PM2 auto-restarts it via systemd on every reboot.</strong></figcaption></figure><p>PM2 kept the Node.js backend running and saved the process list so it auto-restarts through systemd on every reboot — no manual babysitting required.</p><p>First check, locally on the instance:</p><p>curl <a href="http://localhost:5000/api/health">http://localhost:5000/api/health</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*rE8SA9MKW6ZbKu0Is3FWcw.png" /><figcaption><strong>curl http://localhost:5000/api/health<br> Confirms the backend is alive on port 5000 — </strong><strong>{&quot;success&quot;:true,&quot;message&quot;:&quot;Server is running&quot;} — before testing it through the load balancer.</strong></figcaption></figure><p><strong>{“success”:true,”message”:”Server is running”} — backend confirmed alive on port 5000, before I even tried routing traffic through the load balancer.</strong></p><p>Then Nginx, to sit in front of it:</p><p><strong>sudo ln -sf /etc/nginx/sites-available/food-app /etc/nginx/sites-enabled/</strong></p><p><strong>sudo rm -f /etc/nginx/sites-enabled/default</strong></p><p><strong>sudo nginx -t</strong></p><p><strong>sudo systemctl restart nginx</strong></p><p><strong>sudo systemctl enable nginx</strong></p><p><strong>pm2 status</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*d1p9ZP1L6bKNNzmNnVzYjg.png" /><figcaption><strong>Enables the Nginx config, tests it, restarts it, and sets it to start on boot. PM2 shows </strong><strong>food-app online.</strong></figcaption></figure><p>Config enabled, tested, restarted, and set to boot with the system. PM2 showing food-app online at 40.4mb. Full stack, live.</p><h3>9. The Bug That Made Me Actually Understand Security Groups</h3><p>This is the part I almost didn’t include, because it’s the least glamorous — but it’s also the most useful thing that happened during this whole build.</p><p>pm2 restart food-app</p><p>pm2 logs food-app — lines 10</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*rLxgWi0EXcFU0UEsY5ijHA.png" /><figcaption><strong>The debugging moment — </strong><strong>ECONNREFUSED 10.0.4.22:5432. The RDS security group wasn&#39;t allowing the EC2 connection yet.</strong></figcaption></figure><p>ECONNREFUSED 10.0.4.22:5432. The backend couldn’t reach the database. Not a code bug — a security group rule that wasn’t allowing the EC2 instance to talk to RDS. I went back into the Terraform SG rules, fixed the ingress rule, and reapplied.</p><p>pm2 logs food-app — lines 10</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*7hBgjZYDF5rw3Xst-lV1Gw.png" /><figcaption><strong>pm2 logs food-app --lines 10<br> </strong><strong>Connected to PostgreSQL successfully! — fixing the security group rule in Terraform and reapplying solved it</strong>.</figcaption></figure><p>Connected to PostgreSQL successfully! The fix lived entirely in Terraform — no console clicking, no manual rule patch that would’ve been forgotten the next time the environment got rebuilt.</p><h3>10. The Full End-to-End Test</h3><p>curl <a href="http://food-app-dev-alb-1538857620.ap-south-1.elb.amazonaws.com/api/health">http://food-app-dev-alb-1538857620.ap-south-1.elb.amazonaws.com/api/health</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WnF7rqzzOpDCkOu9y8dRKw.png" /></figure><p>{“success”:true,”message”:”Server is running”} — this time from the actual load balancer DNS. Browser → ALB → EC2 → Node.js → Response. The whole path, working, exactly as designed.</p><h3>Shipping It</h3><p>git add .</p><p>git commit -m “food app infrastructure”</p><p>git push origin main</p><p>git branch</p><p>git status</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*um-cfmxs8x4AWs0X-ZzyKw.png" /></figure><p>2 files, 1.46 KiB, pushed to GitHub. The entire AWS setup — VPC, security groups, RDS, EC2, ALB, all of it — is now version controlled and reproducible by anyone who clones the repo and runs terraform apply.</p><h3>What I Actually Took Away From This</h3><p>The AWS Console teaches you what a resource looks like once it exists. Terraform teaches you why it exists that way, because you have to write down every decision — every subnet, every security group rule, every dependency — before anything gets created.</p><p>The two mistakes I made along the way (a config typo and a wrong instance type) turned into one-line fixes instead of afternoon-long fire drills. The security group bug that briefly broke my RDS connection turned into a five-minute Terraform diff instead of a mystery I’d have to reverse-engineer from console settings six months from now.</p><p>If you’re an Associate Cloud Engineer looking to level up, my honest advice: stop practicing on toy examples and build something with real tiers — a network layer, a database layer, a compute layer, and the security boundaries between them. You’ll break something. That’s the point.</p><p><em>If you found this useful, I’d love to hear how your own Terraform builds have gone — especially the mistakes. Those are always the most interesting part.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f1a8fc8e283" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From EC2 to S3: How I Slashed My Frontend Hosting Cost by 95% (AWS Food App — Phase 5)]]></title>
            <link>https://medium.com/@sankalparava619/from-ec2-to-s3-how-i-slashed-my-frontend-hosting-cost-by-95-aws-food-app-phase-5-d09879e592a6?source=rss-d5b9d126ec67------2</link>
            <guid isPermaLink="false">https://medium.com/p/d09879e592a6</guid>
            <category><![CDATA[alb]]></category>
            <category><![CDATA[amazon-rds]]></category>
            <category><![CDATA[amazon-s3]]></category>
            <dc:creator><![CDATA[Sankalparava]]></dc:creator>
            <pubDate>Thu, 07 May 2026 04:29:30 GMT</pubDate>
            <atom:updated>2026-05-07T04:29:30.454Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been building a full-stack food ordering app on AWS — real infrastructure, real services, real learning.</p><p>This is Phase 5 of the project, and it covers one of the most satisfying migrations I’ve done: moving my React frontend off an EC2 instance and onto S3 Static Website Hosting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avJ8oGH1vuMfOCgxNYRnJA.jpeg" /></figure><p>The result? Hosting cost dropped from ~$10–20/month to less than $1/month. Zero server management. Better availability. And a much cleaner architecture. Here’s how it works — and why it matters.</p><p>The Key Insight:</p><p>React Build Output is 100% Static When you run `npm run build`, React compiles, minifies, and bundles your entire app into plain HTML, CSS, and JavaScript files. Once built, these files are identical for every single user who requests them. There’s no reason to run a Node.js server 24/7 just to serve files that never change. That’s the core idea behind this migration.</p><p>What is S3? Amazon S3 (Simple Storage Service) is an object storage service. You store files — called objects — inside containers called buckets, and retrieve them over HTTP. Unlike EC2’s EBS storage (tied to a server), S3 is fully serverless. No machine to manage, no OS to patch, no process to restart. Key S3 properties worth knowing:</p><p>• Durability: 99.999999999% (11 nines) — designed to lose almost nothing <br>• Availability: 99.99% — less than 1 hour of downtime per year • Replication: Automatic across 3+ Availability Zones <br>• Storage limit: Unlimited</p><p>Architecture: Before vs. After Before Phase 5: All traffic hit an Application Load Balancer → React (Node.js on EC2 port 3000) or API (Node.js on EC2 port 5000). The frontend and backend were coupled on the same EC2 — wasteful and fragile.</p><p>After Phase 5:</p><p>• Frontend (HTML/CSS/JS) → S3 Static Website Endpoint — cost: &lt;$1/month • API calls (/api/*) → ALB → EC2 port 5000 (Node.js only) • EC2 now only handles what it actually needs to: dynamic API responses and database queries This separation of concerns is a real-world best practice, not just a cost hack.</p><p>What I Did — Step by Step Step 1:</p><p>Create the S3 Bucket Bucket name: food-app-frontend-2026-sankalp (globally unique, as required by AWS) Region: ap-south-2 (Hyderabad — same as EC2 and RDS) Key settings:</p><p>• Block Public Access → unchecked (required for public hosting) <br>• Default encryption → SSE-S3 (automatic, no extra cost) <br>• ACLs disabled — bucket policies are the right approach Step 2: Build the React App SSH into EC2 → cd into frontend directory → run `npm run build` Output: 12 files, ~1.8 MiB — clean, optimised static assets ready for deployment. Step 3: Upload to S3 Used `aws s3 sync` to copy the build folder to S3: aws s3 sync ~/food-app/frontend/build/ s3://food-app-frontend-2026-sankalp — region ap-south-2 Why `sync` over `cp`? It only uploads new or changed files — faster and cheaper for future deployments.</p><p>Steps 4–6 (In Progress):</p><p>• Enable Static Website Hosting (set index.html as both index and error document)<br> • Apply Bucket Policy to allow public GetObject<br> • Test in browser, fix API base URLs to point to ALB DNS, rebuild, re-sync One Gotcha: React Router and the Error Document Setting the error document to index.html isn’t just a detail — it’s critical. React uses client-side routing. If a user visits /menu directly, S3 looks for a file called “menu”which doesn’t exist.</p><p>Without the error document set, S3 returns 404. When error document = index.html, S3 serves the React app instead, and React Router handles the route in the browser. Without this, every direct URL except the homepage breaks.</p><p>Cost Comparison EC2 Approach S3 Static Hosting Monthly cost $10–20 &lt;$1 Latency 100–200ms 20–50ms Availability 99.9% 99.99% Scalability Manual (ASG) Automatic Management OS, Node, pm2 Zero Deploy downtime Brief restart Zero</p><p>What’s Next: Phase 5B After Phase 5 is complete, Phase 5B adds CloudFront CDN in front of S3:</p><ul><li>Caches files at 400+ edge locations globally</li><li>Latency drops from ~50ms to ~5–10ms • HTTPS via ACM (AWS Certificate Manager) • Custom domain via Route 53 The architecture keeps getting</li><li>cleaner — and the costs stay low.</li></ul><p>Key Takeaway This migration taught me something that sounds obvious but only clicks when you do it: Static content should never live on a server. S3 was literally built for this. EC2 is for compute — for code that needs to run, not files that need to be served. If you’re learning AWS and serving a React frontend from EC2, this is the right next migration to make.</p><p>Phase 5: 50% complete. The bucket is created, the files are uploaded. Enabling hosting, configuring the policy, and testing are next.</p><p>Follow along as I continue building this project — next up is CloudFront, HTTPS, and a custom domain.</p><p>#AWS #CloudComputing #S3 #React #DevOps #CloudArchitecture #LearningInPublic</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d09879e592a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built a Self-Healing Food App on AWS — Auto Scaling from Scratch]]></title>
            <link>https://medium.com/@sankalparava619/how-i-built-a-self-healing-food-app-on-aws-auto-scaling-from-scratch-bb35830340c5?source=rss-d5b9d126ec67------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb35830340c5</guid>
            <dc:creator><![CDATA[Sankalparava]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 04:52:20 GMT</pubDate>
            <atom:updated>2026-04-19T04:52:20.341Z</atom:updated>
            <content:encoded><![CDATA[<p>Part of my ongoing AWS Food App series — building a production-grade app step by step</p><p>There’s a satisfying moment when you stop babysitting your servers and let AWS do it for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tP60B3xM8XF8-b6PUO_QRQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G9-Wv-B-bp5q5yt2-_35oQ.jpeg" /></figure><p>That’s exactly what Phase 4B of my AWS Food App project is about. After setting up an Application Load Balancer with two EC2 instances in Phase 4A, I had a stable setup — but a <em>fixed</em> one. Two instances, always. No more, no less. If traffic spiked at midnight? Both servers would choke. If one crashed at 3 AM? I’d wake up to a broken app and a support ticket.</p><p>Auto Scaling Groups (ASG) fix all of that — automatically, without a single pager alert.</p><p>Here’s how I built it.</p><h3>The Problem with a Static Setup</h3><p>Before adding ASG, my architecture looked like this:</p><pre>User → ALB → [EC2-1 (AZ-a) | EC2-2 (AZ-b)] → RDS</pre><p>Clean. But fragile in ways that only show up under real conditions:</p><ul><li><strong>Traffic spike:</strong> Both EC2 instances overwhelm simultaneously — app slows or crashes</li><li><strong>Instance crash:</strong> I’m down to 1 instance until I manually spin up a replacement</li><li><strong>Low traffic at night:</strong> I’m paying for 2 instances to handle near-zero load</li><li><strong>AZ failure:</strong> Lose one AZ, lose half my capacity with no automatic recovery</li></ul><p>None of these are acceptable in production. ASG solves all four.</p><h3>The Three Building Blocks of Auto Scaling</h3><p>Before touching the console, it’s worth understanding what you’re actually building. ASG isn’t one thing — it’s three things working together:</p><p><strong>1. AMI (Amazon Machine Image)</strong> Think of this as a photograph of your EC2 at its best — OS, Node.js, app code, environment variables, PM2 installed and configured. Every new instance ASG launches starts from this photograph. No manual setup, no missing dependencies.</p><p><strong>2. Launch Template</strong> The blueprint. It tells ASG <em>how</em> to create each new instance: which AMI to use, what instance type (t2.micro in my case), which security group, and what commands to run on first boot (user data). Without this, ASG has no idea what to launch.</p><p><strong>3. Auto Scaling Group</strong> The controller. It watches your CloudWatch metrics, decides when capacity needs to change, and uses the Launch Template to create or terminate instances accordingly. Mine is configured with:</p><ul><li><strong>Desired:</strong> 2 instances (what it tries to maintain)</li><li><strong>Minimum:</strong> 1 (guarantees at least one instance is always running)</li><li><strong>Maximum:</strong> 4 (cost ceiling — won’t create more than 4 even under extreme load)</li></ul><h3>Step 1: Install PM2 on Both EC2 Instances</h3><p>This is the step most tutorials skip, and it causes infinite termination loops when you skip it.</p><p>Here’s the problem: when ASG launches a new instance, the EC2 boots into Ubuntu — but your Node.js app isn’t running. The ALB health checks fail immediately. ASG marks the instance unhealthy and terminates it. Then launches another one. Repeat forever.</p><p>The fix is PM2 — a Node.js process manager that restarts your app automatically on boot.</p><p>bash</p><pre># Install PM2<br>npm install -g pm2</pre><pre># Start both services<br>pm2 start src/index.js --name food-backend<br>pm2 start npm --name food-frontend -- start</pre><pre># THE CRITICAL STEP — don&#39;t skip this<br>pm2 startup<br># Copy and run the command it prints, then:<br>pm2 save</pre><p>The pm2 startup + pm2 save combination is what makes your app survive reboots. Run this on <strong>both</strong> EC2 instances before creating the AMI — because the AMI captures the PM2 configuration, and every future instance inherits it.</p><p>To verify it works, simulate a reboot:</p><p>bash</p><pre>sudo reboot<br># SSH back in after 60 seconds<br>pm2 list  # Both services should show &quot;online&quot;</pre><h3>Step 2: Create a Custom AMI</h3><p>Once PM2 is configured and verified on food-app-server-1, take a snapshot:</p><p>bash</p><pre>aws ec2 create-image \<br>  --instance-id i-05dba1b8c8adebf60 \<br>  --name &#39;food-app-ami&#39; \<br>  --description &#39;Food app with Node.js PM2 and app code&#39; \<br>  --no-reboot</pre><p>The --no-reboot flag keeps your instance running while the AMI is created. Wait 5–15 minutes for status to change to Available before proceeding.</p><p><strong>What the AMI captures:</strong></p><ul><li>Ubuntu OS and all packages</li><li>Node.js installed via nvm</li><li>Your app code in ~/food-app/</li><li>.env file with database credentials</li><li>PM2 installed and configured</li></ul><p><strong>What it doesn’t capture:</strong> running processes (PM2 will restart them via the user data script), temporary files, instance-specific metadata.</p><p>This is why AMI-based launching is so much faster than bootstrapping from scratch — you’re launching a pre-configured instance, not installing everything from zero.</p><h3>Step 3: Create the Launch Template</h3><p>The Launch Template is where you define the config for every future EC2 instance:</p><ul><li><strong>AMI:</strong> your newly created food-app-ami</li><li><strong>Instance type:</strong> t2.micro</li><li><strong>Security group:</strong> food-app-ec2-sg</li><li><strong>Subnet:</strong> leave empty (ASG will assign based on its subnet config)</li><li><strong>User data:</strong> the boot script below</li></ul><p>The user data script is the trickiest part. It runs as <strong>root</strong>, but nvm is installed for the ubuntu user. You have to explicitly switch user context:</p><p>bash</p><pre>#!/bin/bash<br>export HOME=/home/ubuntu<br>export NVM_DIR=&quot;/home/ubuntu/.nvm&quot;<br>[ -s &quot;$NVM_DIR/nvm.sh&quot; ] &amp;&amp; . &quot;$NVM_DIR/nvm.sh&quot;</pre><pre># Start backend<br>cd /home/ubuntu/food-app/backend<br>sudo -u ubuntu bash -c &#39;source /home/ubuntu/.nvm/nvm.sh &amp;&amp; pm2 start src/index.js --name food-backend&#39;</pre><pre># Start frontend<br>cd /home/ubuntu/food-app/frontend<br>sudo -u ubuntu bash -c &#39;source /home/ubuntu/.nvm/nvm.sh &amp;&amp; pm2 start npm --name food-frontend -- start&#39;</pre><pre>sudo -u ubuntu bash -c &#39;source /home/ubuntu/.nvm/nvm.sh &amp;&amp; pm2 save&#39;<br>echo &#39;Food app started via user data script&#39; &gt;&gt; /var/log/food-app-init.log</pre><p>If you run pm2 directly as root without the sudo -u ubuntu wrapper, you&#39;ll get nvm: command not found — and your instance will boot but not serve traffic.</p><h3>Step 4: Create the Auto Scaling Group</h3><p>With the AMI and Launch Template in place, creating the ASG is straightforward:</p><pre>Name: food-app-asg<br>Launch template: food-app-launch-template<br>VPC: food-app-vpc<br>Subnets: private-subnet-1 (AZ-a) + private-subnet-2 (AZ-b)  ← both AZs<br>Load balancer: food-app-alb<br>Target groups: backend-tg + frontend-tg<br>Health check type: ELB  ← critical<br>Health check grace period: 300 seconds<br>Desired: 2 | Min: 1 | Max: 4<br>Scaling policy: Target tracking — Average CPU = 70%</pre><p>A few things worth calling out:</p><p><strong>Private subnets only.</strong> With ALB in front, EC2 instances no longer need public IPs. They receive all traffic through the load balancer. Placing them in private subnets means they’re unreachable from the internet even if someone discovers their IP. NAT Gateway handles their outbound traffic.</p><p><strong>ELB health check type, not EC2.</strong> If you use EC2 health checks, ASG only detects failures at the infrastructure level — if the EC2 is running, ASG considers it healthy, even if your app is crashing. ELB health checks use the ALB’s health check results, which test whether your app is actually responding. This is application-level failure detection.</p><p><strong>300-second grace period.</strong> New instances need time to boot, run the user data script, start PM2, and pass health checks. If the grace period is too short, ASG will terminate instances that are still starting up — creating that infinite loop again.</p><h3>Step 5: Crash Testing — Proving It Actually Works</h3><p>Documenting that HA works on paper isn’t enough. You need to break things and watch ASG fix them.</p><p><strong>Test 1: Kill the app process</strong></p><p>bash</p><pre># SSH into one ASG instance, kill the backend<br>pm2 stop food-backend</pre><pre># Watch the ALB health check in another terminal<br>watch -n 5 &#39;aws elbv2 describe-target-health \<br>  --target-group-arn arn:...:targetgroup/backend-tg/... \<br>  --query &quot;TargetHealthDescriptions[*].{ID:Target.Id,Health:TargetHealth.State}&quot; \<br>  --output table&#39;</pre><p>Expected sequence:</p><ul><li>T+0s: Instance shows healthy</li><li>T+60s: Instance shows unhealthy</li><li>T+90s: ASG detects unhealthy via ELB check</li><li>T+5min: ASG launches replacement from Launch Template</li></ul><p>Throughout this entire sequence, the app should remain available — ALB routes all traffic to the surviving instance.</p><p><strong>Test 2: Stop the entire EC2</strong></p><p>bash</p><pre>aws ec2 stop-instances --instance-ids &lt;INSTANCE_ID&gt;</pre><p>ASG detects that instance count dropped below desired (2 → 1) and automatically launches a replacement. New instance boots, runs user data script, passes health checks, and rejoins the target group.</p><p><strong>Continuous availability check:</strong></p><p>bash</p><pre>for i in {1..20}; do<br>  curl -s -o /dev/null -w &#39;%{http_code}\n&#39; \<br>    http://food-app-alb-xxxx.ap-south-2.elb.amazonaws.com/api/restaurants<br>  sleep 10<br>done<br># All responses should be 200</pre><h3>Step 6: Trigger Scale-Out with a Load Test</h3><p>bash</p><pre># SSH into an instance, install stress<br>sudo apt install stress -y</pre><pre># Stress all CPUs for 5 minutes<br>stress --cpu $(nproc) --timeout 300s &amp;</pre><p>Watch ASG respond:</p><ul><li>T+0min: 2 instances, avg CPU at ~85%</li><li>T+3–5min: CloudWatch alarm triggers, ASG adds a 3rd instance</li><li>T+5min: CPU distributes across 3 instances, drops to ~57%</li><li>T+15min: Stress ends, CPU drops below 30%</li><li>T+20min: After scale-in cooldown, ASG removes the extra instance</li></ul><p>Total scale-out time from CPU spike to new instance healthy: <strong>8–10 minutes</strong>. This includes the CloudWatch evaluation period (3–5 min) plus instance boot time (~5 min).</p><h3>The Architecture After Phase 4B</h3><pre>User → ALB (public subnets)<br>         ↓<br>   food-app-asg<br>   ├── Min: 1 | Desired: 2 | Max: 4<br>   ├── AZ-a: private-subnet-1<br>   │   └── EC2 (from Launch Template)<br>   └── AZ-b: private-subnet-2<br>       └── EC2 (from Launch Template)<br>         ↓<br>        RDS</pre><p>What changed from Phase 4A:</p><ul><li>Instances are in <strong>private subnets</strong> (no public IPs)</li><li>Instance count is <strong>dynamic</strong> — 1 to 4 based on load</li><li>Failures trigger <strong>automatic replacement</strong> in ~3 minutes</li><li>CPU spikes trigger <strong>automatic scale-out</strong> in ~8 minutes</li><li>Night-time low traffic triggers <strong>automatic scale-in</strong> to save cost</li></ul><h3>Key Lessons from This Phase</h3><p><strong>PM2 is non-negotiable.</strong> Without a process manager that survives reboots, ASG-launched instances will boot but never serve traffic. The pm2 startup + pm2 save combination is the foundation everything else rests on.</p><p><strong>User data runs as root — and that breaks nvm.</strong> This caught me off guard. Always use sudo -u ubuntu bash -c &#39;source ~/.nvm/nvm.sh &amp;&amp; ...&#39; when running Node.js commands in user data scripts.</p><p><strong>ELB health checks vs EC2 health checks.</strong> This distinction matters enormously. EC2 health checks can’t detect application failures — only ELB health checks give you true application-level monitoring in ASG.</p><p><strong>The grace period prevents infinite termination loops.</strong> 300 seconds feels long, but new instances genuinely need that time. Too short, and you’ll watch ASG terminate and relaunch instances in an endless cycle.</p><p><strong>AMIs make scaling fast.</strong> A fresh Ubuntu install takes 15–20 minutes. A custom AMI launches in 3–5 minutes. During a traffic spike, those 10 minutes matter.</p><h3>What’s Next</h3><p>Phase 5 will add S3 for static asset storage, CloudFront for global CDN delivery, and Route 53 for custom domain setup. The architecture keeps growing toward production-grade.</p><p>If you’re following along and have questions about any of these steps — AMI creation, user data scripts, health check configuration — drop them in the comments. I’ll be updating this post with actual resource IDs and observed values after running the hands-on session.</p><p><em>This is part of an ongoing series documenting my AWS Food App build. Previous phases covered VPC setup, EC2 deployment, RDS configuration, and ALB + multi-AZ architecture.</em></p><p><em>Region: ap-south-2 (Hyderabad) | Stack: Node.js + React + PostgreSQL on AWS</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb35830340c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Food App Survived an AZ FailureHere’s the AWS Architecture That Made It Possible]]></title>
            <link>https://medium.com/@sankalparava619/my-food-app-survived-an-az-failureheres-the-aws-architecture-that-made-it-possible-c768b0333286?source=rss-d5b9d126ec67------2</link>
            <guid isPermaLink="false">https://medium.com/p/c768b0333286</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[alb]]></category>
            <category><![CDATA[target-group]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[path-based-routing]]></category>
            <dc:creator><![CDATA[Sankalparava]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 14:22:43 GMT</pubDate>
            <atom:updated>2026-04-15T14:22:43.355Z</atom:updated>
            <content:encoded><![CDATA[<p>I added a Production-grade Application Load Balancer to my food delivery app, deployed a second EC2 across a different Availability Zone, fixed 14 separate issues across 3 days of work, and ended with 4/4 targets healthy and zero-downtime AZ failover working live. The animated architecture diagram at the bottom shows exactly how traffic flows — and what happens when an AZ goes down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*rTSQByBAobFpiwn9kFrJAA.jpeg" /></figure><h3>Where We Left Off</h3><p>After Phase 3, my food delivery app had a solid foundation — a Node.js backend, React frontend, and a properly migrated RDS PostgreSQL database. But it had one critical weakness: a single EC2 instance with a public IP that changed every time it restarted.</p><p>That meant if the server crashed — or if I simply stopped it to apply patches — the app went down. Completely. No failover, no rerouting, no safety net.</p><p>Phase 4 was about fixing that. The goal: build a real high-availability setup that could survive an entire Availability Zone failure without the user noticing.</p><p>What I built across 3 days:</p><ul><li>Application Load Balancer with path-based routing</li><li>Second EC2 in a different AZ</li><li>4/4 healthy targets across 2 target groups</li><li>Zero-downtime AZ failover — tested and confirmed</li></ul><p>Here’s every step, every mistake, and every fix.</p><h3>What Phase 4 Actually Introduces</h3><p>Before diving in, here’s the component map:</p><p>BEFORE Phase 4:</p><p>User → hardcoded EC2 IP → single server → RDS</p><p>Problem: IP changes. One crash = full outage.</p><p>AFTER Phase 4:</p><p>User → ALB DNS (permanent) → 2 EC2s across 2 AZs → RDS</p><p>Result: One AZ dies, ALB silently reroutes. Zero downtime.</p><p>The key new components:</p><p><strong>Application Load Balancer (ALB)</strong> — A Layer 7 load balancer that reads HTTP URLs and routes intelligently. Gives you a permanent DNS name that never changes, unlike an EC2 public IP.</p><p><strong>Path-based routing</strong> — The ALB inspects every incoming URL. Requests to /api/* go to the Node.js backend on port 5000. Everything else (/*) goes to the React frontend on port 3000. One DNS entry serves two separate services.</p><p><strong>Target Groups</strong> — Logical groups that map the ALB to specific EC2 instances and ports. backend-tg for Node.js, frontend-tg for React. The ALB runs health checks against each target every 30 seconds.</p><p><strong>Multi-AZ deployment</strong> — Two EC2 instances: server-1 in ap-south-2a and server-2 in ap-south-2b. If an entire AZ fails, the ALB automatically stops routing to that AZ and sends everything to the healthy one.</p><h3>Day 1 — Building the ALB (And Why Health Checks Stayed Unhealthy)</h3><p>Day 1 was about standing up the base infrastructure: a second public subnet in AZ-b, two security groups, two target groups, the ALB itself, and path-based routing rules.</p><p>The security group architecture is worth understanding because it’s what makes this production-grade:</p><p>food-app-alb-sg:</p><p>Inbound: HTTP port 80 from 0.0.0.0/0 (internet → ALB)</p><p>Outbound: All traffic</p><p>food-app-ec2-sg:</p><p>Inbound: Port 3000 from food-app-alb-sg (ALB → React)</p><p>Inbound: Port 5000 from food-app-alb-sg (ALB → Node.js)</p><p>Inbound: SSH from my IP only</p><p>This is security group chaining — the EC2 only accepts traffic that arrives from the ALB’s security group identity, not from the raw internet. Users can no longer bypass the load balancer and hit EC2 directly. The ALB is the single enforced entry point.</p><p>The path-based routing rules:</p><p>Listener: HTTP port 80</p><p>Rule 1 (Priority 1): IF path = /api/* → forward to backend-tg (port 5000)</p><p>Rule 2 (Default): IF path = /* → forward to frontend-tg (port 3000)</p><p>But after setting all of this up — both target groups stayed Unhealthy.</p><p><strong>Mistake 1 — Wrong health check path on backend-tg</strong></p><p>The backend target group had its health check path set to /. Node.js has no route for / — it returns 404. ALB marks the target unhealthy. The fix: change the health check path to /api/restaurants, which exists and returns HTTP 200.</p><p><strong>Mistake 2 — Health check timeout too short</strong></p><p>After fixing the path, targets were still unhealthy. The default timeout was 5 seconds — possibly too short for cold Node.js and React startup responses. Combined with a healthy threshold of 5 consecutive successes, the ALB needed 2.5 minutes of clean responses before declaring anything healthy.</p><p>Diagnosis confirmed the apps were actually fine — curl localhost:5000/api/restaurants returned HTTP 200 instantly. The fix for Day 2: increase timeout to 10 seconds, reduce healthy threshold to 2.</p><h3>Day 2 — Finding the Real Root Cause (It Was Never the Timeout)</h3><p>The timeout fix from Day 1 did nothing. Both target groups were still unhealthy.</p><p>This is the moment where systematic troubleshooting actually matters. I worked layer by layer from inside out:</p><p><strong>Layer 1 — Application layer</strong></p><p>curl <a href="http://localhost:5000/api/restaurants">http://localhost:5000/api/restaurants</a> # HTTP 200</p><p>curl <a href="http://localhost:3000/">http://localhost:3000</a> # HTTP 200</p><p>Apps are running and responding.</p><p><strong>Layer 2 — Network interface</strong></p><p>sudo netstat -tlnp | grep -E ‘3000|5000’</p><p># tcp 0.0.0.0:5000</p><p># tcp 0.0.0.0:3000</p><p>Apps listening on all interfaces — not just localhost.</p><p><strong>Layer 3 — EC2 security group inbound rules</strong></p><p>Checked EC2 SG rules: ports 3000 and 5000 allowed from food-app-alb-sg. Looks correct.</p><p><strong>Layer 4 — ALB security group</strong></p><p>This is where I found it.</p><p>EC2 Console → Load Balancers → food-app-alb → Details tab</p><p>Security groups: sg-024bbd65e6bdce66c ← WRONG</p><p>AWS had auto-attached the <strong>default VPC security group</strong> to the ALB during creation — not food-app-alb-sg. The EC2 security group was configured to accept traffic from food-app-alb-sg. But the ALB was sending traffic from a completely different security group identity. EC2 silently dropped every single packet.</p><p><strong>This is the critical insight:</strong> increasing health check timeout has no effect if EC2 is blocking the request at the network layer before the application can even receive it. No amount of extra wait time fixes a security group mismatch.</p><p>The fix was simple — go to the ALB’s Security tab, remove the default VPC SG, add food-app-alb-sg. Wait 30 seconds. Both target groups turned Healthy.</p><p><strong>Mistake 3 — Frontend hardcoded to EC2 IP</strong></p><p>Even after the ALB was fixed and both targets healthy, the Restaurants page showed blank. Browser console showed: Failed to fetch from <a href="http://18.61.85.106:5000/api/restaurants.">http://18.61.85.106:5000/api/restaurants.</a> The frontend was still calling the EC2 directly — bypassing the ALB entirely.</p><p>Three files needed updating:</p><p>// Before — hardcoded EC2 IP, bypasses ALB entirely</p><p>axios.get(‘http://18.61.85.106:5000/api/restaurants&#39;)</p><p>// After — relative path, works with any load balancer</p><p>axios.get(‘/api/restaurants’)</p><p>Using relative paths (/api/…) is actually better than hardcoding the ALB DNS too. When the browser receives the React app from the ALB, it sends API calls to the same host that served it — which is the ALB. The ALB then routes /api/* to the backend. No hostname anywhere in the code.</p><p><strong>Mistake 4 — App listening on 127.0.0.1 instead of 0.0.0.0</strong></p><p>For the React frontend specifically, it must be started with HOST=0.0.0.0 npm start. Without this, React binds to localhost only. The ALB’s health check request arrives at the EC2’s private IP — which is a different interface — and gets refused. netstat should always show 0.0.0.0:3000, never 127.0.0.1:3000.</p><h3>Day 3 — Multi-AZ High Availability Complete</h3><p>With the ALB fully operational on one EC2, Day 3 was about achieving actual high availability — adding a second EC2 in a different Availability Zone.</p><p><strong>Second EC2 setup:</strong></p><p>food-app-server-1: ap-south-2a | i-05dba1b8c8adebf60 | 10.0.1.218</p><p>food-app-server-2: ap-south-2b | i-0b6f46e1b4a36aa3b | 10.0.4.15</p><p>Both instances run the same stack: Node.js backend on port 5000, React frontend on port 3000.</p><p><strong>Mistakes on Day 3:</strong></p><p><strong>Mistake 5 — Wrong RDS master username</strong></p><p>Connection to RDS was failing. The master username wasn’t postgres as assumed — it was foodapp_user. Found it with:</p><p>aws rds describe-db-instances \</p><p>— db-instance-identifier food-app-rds \</p><p>— query ‘DBInstances[0].MasterUsername’ — output text</p><p># Output: foodapp_user</p><p><strong>Mistake 6 — SSL not in db.js again (on the new EC2)</strong></p><p>Same as Phase 3. Setting up the second EC2 from scratch, the db.js file needed the SSL config added. RDS enforces encrypted connections — it’s never optional.</p><p>const pool = new Pool({</p><p>host: process.env.DB_HOST,</p><p>port: process.env.DB_PORT,</p><p>database: process.env.DB_NAME,</p><p>user: process.env.DB_USER,</p><p>password: process.env.DB_PASSWORD,</p><p>ssl: { rejectUnauthorized: false }</p><p>});</p><p><strong>Mistake 7 — Hardcoded credentials instead of environment variables</strong></p><p>This time we fixed it properly from the start — .env files on both EC2 instances, dotenv package installed, credentials out of source code entirely:</p><p>cat &gt; ~/food-app/backend/.env &lt;&lt; ‘EOF’</p><p>DB_HOST=food-app-rds.cbmuoumuyill.ap-south-2.rds.amazonaws.com</p><p>DB_PORT=5432</p><p>DB_NAME=foodappdb</p><p>DB_USER=foodapp_user</p><p>DB_PASSWORD=FoodApp2024!</p><p>PORT=5000</p><p>EOF</p><p><strong>Mistake 8 — RDS security group using IP addresses instead of SG reference</strong></p><p>The original RDS security group rule allowed connections from specific EC2 IP addresses. When EC2s restart, IPs change. When Auto Scaling adds new instances, their IPs aren’t in the rule. The fix: change the source from 10.0.1.218/32 to food-app-ec2-sg. Any EC2 with that security group can connect automatically — no manual updates ever needed.</p><p><strong>Mistake 9 — Only registered one EC2 to target groups</strong></p><p>After setting up the second EC2, only server-1 was in both target groups. For actual load distribution and redundancy, both instances need to be in both groups:</p><p># Register second EC2 to backend-tg</p><p>aws elbv2 register-targets \</p><p>— target-group-arn arn:aws:…:targetgroup/backend-tg/… \</p><p>— targets Id=i-0b6f46e1b4a36aa3b,Port=5000</p><p># Register second EC2 to frontend-tg</p><p>aws elbv2 register-targets \</p><p>— target-group-arn arn:aws:…:targetgroup/frontend-tg/… \</p><p>— targets Id=i-0b6f46e1b4a36aa3b,Port=3000</p><p>Final target health:</p><p>Target Group EC2 Port AZ Status</p><p>backend-tg server-1 5000 ap-south-2a Healthy</p><p>backend-tg server-2 5000 ap-south-2b Healthy</p><p>frontend-tg server-1 3000 ap-south-2a Healthy</p><p>frontend-tg server-2 3000 ap-south-2b Healthy</p><p>4/4. Both AZs. Full redundancy.</p><h3>The AZ Failure Test</h3><p>With 4/4 targets healthy, I simulated AZ failures using the animated architecture (embedded below). The results:</p><p><strong>AZ-a failure</strong> — server-1 fails health checks. ALB detects it within 30 seconds (2 consecutive failures × 15s interval). All traffic automatically reroutes to server-2 in AZ-b. Users see nothing. The app keeps working.</p><p><strong>AZ-b failure</strong> — Same in reverse. server-2 fails, everything goes to server-1. No downtime.</p><p>This is what high availability actually means: not “the server is fast” but “the system keeps running when individual components fail.”</p><h3>The Final Architecture</h3><p>Region: ap-south-2 (Hyderabad)</p><p>└── food-app-vpc (10.0.0.0/16)</p><p>│</p><p>├── Internet Gateway</p><p>│</p><p>├── ALB — food-app-alb (spans both AZs)</p><p>│ ├── /api/* → backend-tg → Node.js port 5000</p><p>│ └── /* → frontend-tg → React port 3000</p><p>│</p><p>├── Public Subnet AZ-a (10.0.1.0/24)</p><p>│ └── food-app-server-1 — Node.js + React</p><p>│</p><p>├── Public Subnet AZ-b (10.0.4.0/24)</p><p>│ └── food-app-server-2 — Node.js + React</p><p>│</p><p>└── Private Subnet AZ-a (10.0.2.0/24)</p><p>└── RDS PostgreSQL — foodappdb — SSL — encrypted</p><h3>What’s Still Missing (Being Honest)</h3><p><strong>HTTPS is not configured.</strong> The ALB currently only listens on HTTP port 80. Production requires an HTTPS listener on port 443 using AWS Certificate Manager. Port 80 should redirect to 443. This comes in Phase 5 with Route 53 and ACM.</p><p><strong>EC2 instances are still in public subnets.</strong> With an ALB in front, the EC2s don’t need public IPs at all — they should live in private subnets and receive traffic only from the ALB. Phase 4B (Auto Scaling) will move new instances to private subnets.</p><p><strong>No Auto Scaling yet.</strong> The current setup handles AZ failure but not load spikes. If traffic suddenly multiplies, both EC2s could be overwhelmed. Phase 4B adds an Auto Scaling Group with a target tracking policy (scale out if average CPU &gt; 70%).</p><p><strong>ALB access logs not enabled.</strong> Without access logging to S3, there’s no record of which requests hit the ALB, which targets they went to, or what the response codes were. For production debugging this is essential.</p><h3>The Key Lessons — All 9 of Them</h3><p><strong>Always verify the security group actually attached to a newly created resource.</strong> AWS sometimes auto-selects the default VPC SG. Check the Details tab of any ALB, RDS, or EC2 after creation.</p><p><strong>Security group chaining is more powerful than IP rules.</strong> Referencing another SG as a source is dynamic, automatic, and correct even when IPs change or Auto Scaling adds new instances.</p><p><strong>Health check path must return HTTP 200.</strong> Test your health check path manually before creating target groups. / returning 404 from your backend is a very common mistake.</p><p><strong>Apps must listen on 0.0.0.0, not 127.0.0.1.</strong> The React HOST=0.0.0.0 flag is easy to forget. netstat is your friend.</p><p><strong>Troubleshoot inside out.</strong> Application → network interface → EC2 SG → ALB SG → subnets → health check path. Don’t jump to complex solutions before checking each layer.</p><p><strong>Relative API paths beat hardcoded hostnames.</strong> /api/restaurants works behind any load balancer, any DNS, any server. <a href="http://18.61.85.106:5000/api/restaurants">http://18.61.85.106:5000/api/restaurants</a> breaks the moment the IP changes.</p><p><strong>Use SG references in RDS rules, never IP addresses.</strong> Especially when Auto Scaling is next — you can’t manually add every new instance’s IP to the RDS rule.</p><p><strong>Environment variables are not optional.</strong> Credentials in source code is a security risk. .env + .gitignore is the minimum viable approach.</p><p><strong>High availability means the system handles failure, not that failure never happens.</strong> Two EC2s across two AZs means one can completely die and users never notice. That’s the goal.</p><h3>What’s Next — Phase 4B</h3><p>The foundation is solid. Next session: crash testing, Auto Scaling Group, and Launch Templates.</p><p>The plan:</p><ol><li>Create an AMI from the current working EC2</li><li>Build a Launch Template using that AMI</li><li>Create an Auto Scaling Group with desired=2, min=1, max=4</li><li>Test by terminating an instance and watching ASG automatically launch a replacement</li><li>Verify new instance joins the target groups and receives traffic</li><li>After Phase 4B, the architecture will be fully elastic — handling both failures and load spikes automatically. Phase 5 will add HTTPS with ACM and a custom domain via Route 53.</li></ol><p>The journey continues.</p><p><em>This is part of my Cloud Engineering learning series — Phase 1 through Phase 4, all documented with real mistakes and real fixes. Previous: [I Migrated to AWS RDS and Accidentally Put My Database on a Public Subnet.]</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c768b0333286" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Migrated to AWS RDS and Accidentally Put My Database on a Public Subnet]]></title>
            <link>https://medium.com/@sankalparava619/i-migrated-to-aws-rds-and-accidentally-put-my-database-on-a-public-subnet-e359f23b8ef7?source=rss-d5b9d126ec67------2</link>
            <guid isPermaLink="false">https://medium.com/p/e359f23b8ef7</guid>
            <dc:creator><![CDATA[Sankalparava]]></dc:creator>
            <pubDate>Sun, 29 Mar 2026 07:36:12 GMT</pubDate>
            <atom:updated>2026-03-29T07:36:12.187Z</atom:updated>
            <content:encoded><![CDATA[<p>Three mistakes, two hours of migration, zero data lost. Here’s everything that went wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*k7zINISf6cwnuO2v1dfKPg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*fc_gjrwS8Mc7gAXMq4NvSA.jpeg" /></figure><p>I migrated a manually managed PostgreSQL database on EC2 to AWS RDS. The migration took 2 hours, zero rows were lost — but I made three real mistakes along the way: I misunderstood what IaaS vs PaaS actually means, I trusted a subnet <em>name</em> instead of checking the route table, and I forgot RDS enforces SSL. This is the full honest story.</p><h3>It Started With Three Mistakes I Didn’t Know I Was Making</h3><p><strong>Mistake #1</strong> I thought using the AWS Console made everything SaaS.</p><p><strong>Mistake #2</strong> I created an RDS instance and put it on a public subnet — and only found out by accident.</p><p><strong>Mistake #3</strong> I updated my Node.js app to point at RDS and got a connection refused error that had nothing to do with networking. It was SSL.</p><p>None of these are obvious. All of them are completely avoidable. Let me walk you through each one — and what I actually learned from building a real PostgreSQL-to-RDS migration for my food delivery app.</p><h3>The Context — Why I Migrated at All</h3><p>It was Sunday morning when I realized I’d forgotten to check my backup script. Again.</p><p>I SSH-ed into my EC2 database instance, navigated to /var/backups/postgresql, and stared at the log files trying to figure out if last night&#39;s backup had actually run — or had silently failed like the week before.</p><p>That moment crystallized something I’d been ignoring: I was spending more time <em>managing</em> my database than <em>building</em> my application.</p><p>Here’s what the math looked like when I finally sat down to calculate it:</p><p>TaskTime per monthBackup verification30 min/week = 2 hrsLog checking20 min/week = 1.5 hrsPerformance monitoring30 min/week = 2 hrsSecurity patches2 hrsPostgreSQL updates1 hrBackup testing1 hr<strong>Total~8 hours/month</strong></p><p>At a conservative $50/hour, that’s <strong>$400/month in time</strong> to manage a database that costs <strong>$10/month</strong> on EC2.</p><p>RDS costs $16/month and handles all of that automatically.</p><p>The decision wasn’t hard. The migration, however, taught me more than I expected.</p><h3>Part 1 — The Misconception I Had to Unlearn First</h3><p>Before touching a single AWS resource, I need to address something that confused me for weeks — because I suspect it confuses most beginners.</p><p><strong>I thought: “I use the AWS Console to create EC2, RDS, VPCs. I’m clicking buttons in a web UI. Isn’t that all SaaS?”</strong></p><p>No. Absolutely not. And understanding why is the key to making good cloud architecture decisions.</p><p><strong>The Classification Isn’t About How You Create — It’s About What You Manage After</strong></p><p>The AWS Console is just the ordering tool. What matters is what lands on your plate after you click “Create.”</p><p>Here’s the analogy that finally made it click for me:</p><p><strong>Scenario 1: You Rent a Kitchen (IaaS)</strong></p><p>You use a website to rent a commercial kitchen. Easy — just click and pay. But after you rent it, you buy ingredients, cook everything, clean up, maintain equipment, and handle food safety. The website was just for ordering. The actual work is all yours.</p><p><em>This is EC2.</em> AWS Console = the website. The EC2 instance = the kitchen. You manage everything inside it: the OS, the runtime, the database software, the patches, the backups.</p><p><strong>Scenario 2: You Order a Meal Kit (PaaS)</strong></p><p>Same website, different product. Your ingredients are pre-measured, the recipe is included, you just cook and eat. No shopping, no prep cleanup.</p><p><em>This is RDS.</em> AWS Console = the website. RDS = the meal kit. AWS manages PostgreSQL installation, OS patches, backups, and failover. You manage only your data and schema.</p><p><strong>Scenario 3: You Order Delivery (SaaS)</strong></p><p>Same website. You click order, you eat. That’s literally it.</p><p><em>This is AWS Secrets Manager or SNS.</em> You just call the API. Everything else is AWS’s problem.</p><p><strong>How My Food App’s Services Break Down</strong></p><p>IaaS:<br> EC2 (App Server) → I manage: OS, Node.js, app code, patches<br> VPC → I manage: subnets, route tables, security groups<br> EBS → I manage: filesystem, data, backups</p><p>PaaS:<br> RDS → I manage: schema and data only<br> ALB (coming Phase 4) → I manage: routing rules only</p><p>SaaS:<br> Secrets Manager → I just store and retrieve. AWS handles everything else.</p><p>The key insight: <strong>migrating from EC2 PostgreSQL to RDS means moving up the stack from IaaS to PaaS.</strong> Less management, more focus on your actual application.</p><h3>Part 2 — The Architecture Before Migration</h3><p>My food delivery app was running on a two-tier setup:</p><pre>Internet<br>    ↓<br>Internet Gateway<br>    ↓<br>Public Subnet (10.0.1.0/24)<br>    └── App EC2 — React frontend + Node.js backend<br>        Public IP: 16.112.128.36<br>        ↓<br>Private Subnet (10.0.2.0/24)<br>    └── DB EC2 — Ubuntu + PostgreSQL 16.13<br>        Private IP: 10.0.2.94<br>        Database: foodapp<br>        Tables: restaurants, menu_items, orders</pre><p>It worked. Users could browse restaurants, view menus, place orders. The database was in a private subnet, secured behind security groups.</p><p>But “it works” and “it’s well-managed” are very different things. And I was doing the database management equivalent of maintaining a car engine by hand when I could have been leasing one that serviced itself.</p><h3>Part 3 — The Migration — Step by Step</h3><p>The full migration took about 2 hours and involved 9 steps. Zero data was lost.</p><p><strong>Step 1 — Create the RDS Infrastructure</strong></p><p><strong>DB Subnet Group first.</strong> Before launching RDS, I needed a subnet group — telling RDS which subnets it could use. I created one spanning two private subnets across two availability zones (required for Multi-AZ, good practice even for single-AZ).</p><p><strong>RDS Security Group.</strong> Created a new security group with one inbound rule:</p><pre>Type: PostgreSQL | Port: 5432 | Source: App EC2 Security Group</pre><p>No public access. Only the app server can talk to the database.</p><p><strong>Launch RDS instance</strong></p><pre>Engine:       PostgreSQL 16.13<br>Instance:     db.t3.micro<br>Storage:      20 GB gp3<br>VPC:          food-app-vpc<br>Subnet Group: food-app-db-subnet-group (private subnets)<br>Public Access: No<br>Encryption:   Yes (AWS KMS)<br>Backups:      7-day retention</pre><p>Wait 5–10 minutes.</p><p>Endpoint after launch:</p><pre>food-app-rds.cbmuoumuyill.ap-south-2.rds.amazonaws.com:5432</pre><p>This endpoint never changes — even if AWS moves the database to different hardware underneath.</p><p><strong>Step 2 — Export Data from EC2</strong></p><p>SSH into the old DB EC2 and export with pg_dump:</p><p>bash</p><pre>ssh -i ~/.ssh/dbapp1.pem ubuntu@10.0.2.94<br>pg_dump -U foodapp_user -d foodapp -h localhost &gt; ~/foodapp_backup.sql</pre><p>Verify the backup looks healthy:</p><p>bash</p><pre>ls -lh ~/foodapp_backup.sql<br># -rw-rw-r-- 1 ubuntu ubuntu 8.0K Mar 27 05:42 foodapp_backup.sql</pre><pre>head -20 ~/foodapp_backup.sql<br># -- PostgreSQL database dump<br># -- Dumped from database version 16.13<br># CREATE TABLE public.restaurants (...)</pre><p>What pg_dump exports: table schemas, all data, sequences for auto-increment IDs, indexes and constraints — everything in a human-readable SQL file.</p><p><strong>Step 3 — Transfer to App EC2</strong></p><p>The App EC2 has network access to RDS (the DB EC2 doesn’t). So I copied the backup there:</p><p>bash</p><pre># From App EC2:<br>scp -i ~/.ssh/dbapp1.pem ubuntu@10.0.2.94:~/foodapp_backup.sql ~/</pre><p><strong>Step 4 — Import into RDS</strong></p><p>Install the PostgreSQL client on the App EC2:</p><p>bash</p><pre>sudo apt update &amp;&amp; sudo apt install postgresql-client -y</pre><p>Test the connection first:</p><p>bash</p><pre>psql -h food-app-rds.cbmuoumuyill.ap-south-2.rds.amazonaws.com \<br>     -U foodapp_user -d postgres -p 5432</pre><p>Create the database, then restore:</p><p>bash</p><pre># In psql:<br>CREATE DATABASE foodapp;<br>\q</pre><pre># Restore:<br>psql -h food-app-rds.cbmuoumuyill.ap-south-2.rds.amazonaws.com \<br>     -U foodapp_user -d foodapp -p 5432 \<br>     &lt; ~/foodapp_backup.sql</pre><p>Expected output:</p><pre>COPY 16   ← menu_items restored<br>COPY 2    ← orders restored<br>COPY 4    ← restaurants restored</pre><p><em>Note:</em> You might see “role postgres does not exist” errors. These are harmless — RDS uses your master user instead of the default postgres role.</p><p><strong>Step 5 — Verify Data Integrity</strong></p><p>Never skip this. Connect to RDS and check your row counts match exactly:</p><p>sql</p><pre>SELECT &#39;restaurants&#39; AS table_name, COUNT(*) AS rows FROM restaurants<br>UNION ALL<br>SELECT &#39;menu_items&#39;, COUNT(*) FROM menu_items<br>UNION ALL<br>SELECT &#39;orders&#39;, COUNT(*) FROM orders;</pre><pre>table_name  | rows<br>-------------+------<br> restaurants |    4<br> menu_items  |   16<br> orders      |    2</pre><p>All rows present and accounted for.</p><p><strong>Step 6 — Update Application Config</strong></p><p>The only code change required — update db.js to point at RDS:</p><p><strong>Before (EC2)</strong></p><p>javascript</p><pre>const pool = new Pool({<br>  host: &#39;10.0.2.94&#39;,  // EC2 private IP<br>  port: 5432,<br>  database: &#39;foodapp&#39;,<br>  user: &#39;foodapp_user&#39;,<br>  password: &#39;foodapp123&#39;,<br>});</pre><p><strong>After (RDS)</strong></p><p>javascript</p><pre>const pool = new Pool({<br>  host: &#39;food-app-rds.cbmuoumuyill.ap-south-2.rds.amazonaws.com&#39;,<br>  port: 5432,<br>  database: &#39;foodapp&#39;,<br>  user: &#39;foodapp_user&#39;,<br>  password: &#39;foodapp123&#39;,<br>  ssl: { rejectUnauthorized: false }  // RDS requires SSL<br>});</pre><p>Two changes: endpoint instead of IP, and SSL enabled (RDS enforces encrypted connections).</p><p><strong>Step 7 — Test Everything</strong></p><p>Start the backend:</p><p>bash</p><pre>node src/index.js<br># Backend running on http://localhost:5000<br># Connected to PostgreSQL successfully! </pre><p>Test the API:</p><p>bash</p><pre>curl http://localhost:5000/api/restaurants<br># Returns all restaurants from RDS </pre><p>Open the browser, place a test order, verify the order appears in RDS. Full end-to-end working.</p><p><strong>Step 8 — Cleanup</strong></p><p>Stop (don’t terminate yet) the old DB EC2. Keep it for a few days as a safety net, then terminate once you’re confident RDS is solid.</p><h3>Part 4 — The Problem I Didn’t Expect — RDS on a Public Subnet</h3><p>This is the part I’m most glad I caught before going to production.</p><p>After setting everything up, I was reviewing my VPC subnets and noticed something odd:</p><pre>Subnets in my VPC:<br>├── pub-food-ap-sub (10.0.1.0/24)<br>├── RDS-Pvt-subnet-1 (10.0.0.128/25)  ← Where did this come from?<br>├── food-app-private-subnet-1 (10.0.2.0/24)<br>└── food-app-private-subnet-2 (10.0.3.0/24)</pre><p>I clicked on RDS-Pvt-subnet-1 and checked its route table:</p><pre>Routes:<br>├── 10.0.0.0/16 → local<br>└── 0.0.0.0/0   → igw-xxxxx   ← Internet Gateway!</pre><p>My “private” RDS subnet had a route to the Internet Gateway. <strong>It was effectively a public subnet.</strong></p><p><strong>How Did This Happen?</strong></p><p>When I first tried creating RDS, I used the AWS Console’s “Connect to EC2” quick option. AWS auto-created a subnet group — but placed it in a subnet associated with the <em>public</em> route table. The name said “private.” The routing said otherwise.</p><p>This is why you always check route tables, not just subnet names.</p><p><strong>Why It Matters</strong></p><ul><li>RDS becomes internet-facing (even with “Public Access: No”)</li><li>Violates the principle of network isolation</li><li>Creates a potential attack surface</li><li>Fails compliance requirements in production</li></ul><p><strong>The Fix</strong></p><p>You can’t move an RDS instance between subnet groups after creation. So the fix required:</p><ol><li><strong>Take a snapshot</strong> of the current RDS</li><li><strong>Delete</strong> the incorrectly placed RDS instance</li><li><strong>Create a proper DB subnet group</strong> using only genuinely private subnets</li><li><strong>Restore from snapshot</strong> into the correct subnet group</li></ol><p>After restoring, I verified the route table — 0.0.0.0/0 → NAT Gateway only. No internet gateway. Database properly isolated. ✅</p><p><strong>Lesson</strong> Always verify subnet placement by checking the route table, not just the subnet name. A subnet is only private if its route table sends internet traffic through a NAT Gateway, not an Internet Gateway.</p><h3>Part 5 — The Before vs After</h3><p><strong>Architecture After Migration</strong></p><pre>Internet<br>    ↓<br>Internet Gateway<br>    ↓<br>Public Subnet (10.0.1.0/24)<br>    └── App EC2 — React + Node.js<br>        ↓ (port 5432, internal only)<br>Private Subnet (10.0.2.0/24)<br>    └── RDS PostgreSQL<br>        ├── Automated backups ✅<br>        ├── Automated patching ✅<br>        ├── Point-in-time recovery ✅<br>        ├── Encryption at rest ✅<br>        └── SSL in transit ✅</pre><p><strong>The Real Comparison</strong></p><p>What I used to do manuallyWhat RDS does automaticallyRun pg_dump backup scriptsDaily full backups + 5-min transaction logsCheck if backups ranAutomatic verificationApply OS security patchesHandled by AWSUpgrade PostgreSQL versionsManaged maintenance windowsMonitor disk/CPU manuallyCloudWatch metrics built-inSet up read replicasFew clicks in consoleHandle failover manuallyAutomatic with Multi-AZ</p><p><strong>Cost Breakdown</strong></p><p>EC2 PostgreSQLRDS PostgreSQLAWS infrastructure cost$10/month$16/monthMonthly management time8 hours0 hoursTime cost (@$50/hr)$400/month$0<strong>Total real cost$410/month$16/monthAnnual saving$4,728</strong></p><p>The $6/month extra for RDS is the best $6 I’ve ever spent.</p><h3>The Three Mistakes — Summarised</h3><p><strong>Mistake #1 — Thinking the AWS Console = SaaS.</strong> The console is just the ordering tool. What matters is what you manage <em>after</em> you click create. EC2 PostgreSQL = you manage everything. RDS = you manage only your data. Same console, completely different responsibility split.</p><p><strong>Mistake #2 — Trusting a subnet name instead of the route table.</strong> “RDS-Pvt-subnet” sounds private. A route pointing to igw-xxxxx says otherwise. A subnet is only truly private if its route table sends internet traffic through a <em>NAT Gateway</em>, not an Internet Gateway. Always check the routes, never the name.</p><p><strong>Mistake #3 — Forgetting RDS enforces SSL.</strong> When you switch from EC2 PostgreSQL to RDS and get ECONNREFUSED, your first instinct is to check security groups and IPs. The actual fix is one line: ssl: { rejectUnauthorized: false } in your connection config. RDS requires encrypted connections — it&#39;s not optional.</p><p><strong>Bonus lesson: Migrations are less scary with a rollback plan.</strong> Taking a snapshot before every destructive action meant I could always go back. The RDS-in-wrong-subnet problem? Fixed in under 30 minutes because I had a clean snapshot to restore from. Zero data loss, zero panic.</p><h3>What’s Next — Phase 4</h3><p>The database layer is now managed, secure, and automated. Next up: adding an <strong>Application Load Balancer (ALB)</strong> in front of the app server.</p><p>This moves from a direct EC2 public IP (fragile, single point of failure) to a proper load-balanced setup — the foundation for Auto Scaling and high availability.</p><p>Phase 4 coming soon. Follow along if you’re on the same journey.</p><p><em>This is part of my Cloud Engineering learning series. Each week I build something real, break something, fix it, and document everything. Previous post: Building a Secure Two-Tier AWS Architecture from Scratch.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e359f23b8ef7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Broke My AWS Infrastructure and Learned More Than Any Tutorial Ever Taught Me]]></title>
            <link>https://medium.com/@sankalparava619/i-broke-my-aws-infrastructure-and-learned-more-than-any-tutorial-ever-taught-me-40eb562dd0f6?source=rss-d5b9d126ec67------2</link>
            <guid isPermaLink="false">https://medium.com/p/40eb562dd0f6</guid>
            <category><![CDATA[aws-traffic]]></category>
            <category><![CDATA[vpc]]></category>
            <category><![CDATA[mysql-8]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[ec2]]></category>
            <dc:creator><![CDATA[Sankalparava]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 04:59:51 GMT</pubDate>
            <atom:updated>2026-03-23T04:59:51.064Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>From Zero to Two-Tier: How I Built a Secure AWS Architecture in My First Week as a Cloud Engineer</strong></p><p><em>A hands-on journey through VPCs, NAT Gateways, MySQL, broken infrastructure, and the troubleshooting that actually teaches you cloud.</em></p><p><strong>The Goal</strong></p><p>When I started my cloud engineering learning journey, I didn’t want to just watch tutorials and tick theoretical boxes. I wanted to <strong>build something real </strong>something that broke, something I had to fix, something that taught me why AWS services exist, not just what they are.</p><p><strong>Week 1 objective:</strong> Deploy a two-tier architecture on AWS, with a frontend application in a public subnet and a MySQL database locked away in a private subnet. Simple on paper. Surprisingly deep in practice.</p><p><strong>What I Actually Built</strong></p><p>Here’s the architecture at a glance:</p><p>User<br>↓</p><p>Internet</p><p>↓</p><p>Internet Gateway</p><p>↓</p><p>Public Subnet</p><p>├── Application EC2 (Nginx + Node.js API)</p><p>└── NAT Gateway</p><p>↓</p><p>Private Subnet</p><p>└── Database EC2 (MySQL)</p><p>The rule of thumb: <strong>the internet can reach your app, but it can never directly touch your database.</strong> That separation is the foundation of secure cloud architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*IfW8VW97aU2OTYvCKr2x6g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*MblxLMDKL4EbTsQM3RZmvQ.jpeg" /></figure><p><strong>Phase 1 — Standing Up the Network</strong></p><p>Before launching a single EC2 instance, I had to build the network it would live in.</p><p><strong>VPC first.</strong> A Virtual Private Cloud is your isolated slice of AWS networking think of it as renting a section of a data center where you control all the routing rules.</p><p>Then came subnets — a <strong>public subnet </strong>(for resources that need internet access) and a <strong>private subnet</strong>(for resources that should never be directly reachable from the outside world).</p><p>Key configuration detail that trips up beginners: when creating the private subnet, you must <strong>disable auto-assign public IP</strong>. Without doing this explicitly, your “private” server will happily accept a public IP and expose itself.</p><p>Next, I attached an <strong>Internet Gateway </strong>to the VPC and configured route tables:</p><p>| Subnet | Destination | Target |</p><p>| — -| — -| — -|</p><p>| Public | 0.0.0.0/0 | Internet Gateway |</p><p>| Private | 0.0.0.0/0 | NAT Gateway |</p><p>The NAT Gateway is what makes the private subnet practical — it lets your database EC2 reach the internet for package installs and updates, while remaining completely unreachable from the outside.</p><p><strong>Phase 2 — Deploying the Application Layer</strong></p><p>With the network in place, I launched the application EC2 in the public subnet, installed Nginx as the web server, and deployed a frontend application.</p><p>Security group rules for the app server:</p><p>SSH (22) → My IP only</p><p>HTTP (80) → 0.0.0.0/0</p><p>This is the principle of <strong>least privilege in action </strong>only open the ports you need, only to the sources that need them.</p><p><strong>Phase 3 — The Database Layer (And Where Things Got Interesting)</strong></p><p>The database EC2 lives in the private subnet with no public IP. The only way in is through the application server, acting as a <strong>Bastion Host</strong> (Jump Host):</p><p>bash</p><p># Step 1: SSH into the public EC2</p><p>ssh ubuntu@&lt;public-ec2-ip&gt;</p><p># Step 2: From there, hop into the private EC2</p><p>ssh -i key.pem ubuntu@&lt;private-ec2-ip&gt;</p><p>The security group on the database EC2 is deliberately restrictive:</p><p>Inbound SSH (22) → Application EC2 Security Group only</p><p>Inbound MySQL (3306) → Application EC2 Security Group only</p><p>Outbound → All traffic allowed (for package installs via NAT)</p><p>Notice what’s missing: <strong>no inbound rule from 0.0.0.0/0</strong>. The database is invisible to the internet.</p><p><strong>Phase 4 — The Troubleshooting That Taught Me the Most</strong></p><p>This is where the real learning happened.</p><p><strong>Problem 1: Private EC2 Had No Internet Access</strong></p><p>After setting everything up, my private EC2 couldn’t reach the internet at all:</p><p>bash</p><p>ping 8.8.8.8 # 100% packet loss</p><p>curl <a href="https://google.com/">https://google.com</a> # Connection failed</p><p>sudo apt update # Unable to fetch packages</p><p>I went through a systematic diagnosis:</p><p>- Checked Network ACLs — missing ephemeral port rules (1024–65535). Added them. Still broken.</p><p>- Verified the route table — route to NAT Gateway looked correct. Still broken.</p><p>- Checked security groups — outbound all traffic. Still broken.</p><p>Then I inspected the NAT Gateway itself via AWS CLI and found the root cause:</p><p>SubnetId: null</p><p>The NAT Gateway had been <strong>created without a proper subnet association**</strong>. It existed, but it was functionally useless. The fix: delete the broken NAT Gateway, allocate a fresh Elastic IP, create a new NAT Gateway in the correct public subnet, and update the route table.</p><p>bash</p><p>aws ec2 delete-nat-gateway — nat-gateway-id nat-146586e2783e08021</p><p>aws ec2 create-nat-gateway — subnet-id &lt;PUBLIC_SUBNET_ID&gt; — allocation-id &lt;EIP_ID&gt;</p><p>aws ec2 replace-route — route-table-id &lt;RTB_ID&gt; — destination-cidr-block 0.0.0.0/0 — nat-gateway-id nat-0f1f2ab50527f076c</p><p>Result: `ping 8.8.8.8` came back with 0% packet loss. That moment felt genuinely satisfying.</p><p><strong>Problem 2: Node.js API Couldn’t Reach MySQL</strong></p><p>After setting up the Node.js backend on the public EC2, the app couldn’t connect to the database:</p><p>connect ECONNREFUSED 127.0.0.1:3306</p><p>Cause: The `host` in the database config was still set to `localhost`. Changed it to the private EC2’s internal IP: `10.0.2.66`.</p><p>New error:</p><p>connect ECONNREFUSED 10.0.2.66:3306</p><p>Checked MySQL’s listening interfaces:</p><p>bash</p><p>sudo ss -tlnp | grep mysql</p><p>Result: MySQL listening on 127.0.0.1:3306 only</p><p>MySQL was bound to localhost only. Fix: edit /etc/mysql/mysql.conf.d/mysqld.cnf` and change:</p><p>bind-address = 127.0.0.1</p><p>to:</p><p>bind-address = 0.0.0.0</p><p><strong>Problem 3: MySQL User Permission Denied</strong></p><p>After fixing the binding, a new error appeared:</p><p>Host ‘10.0.1.169’ is not allowed to connect to this MySQL server</p><p>Root user is restricted to localhost by design. The correct solution is <strong>**not**</strong> to relax root permissions — it’s to create a dedicated application user:</p><p>sql</p><p>CREATE USER ‘appuser’ IDENTIFIED BY ‘SecurePassword’;</p><p>GRANT ALL PRIVILEGES ON test_db.* TO ‘appuser’;</p><p>FLUSH PRIVILEGES;</p><p>This is the <strong>principle of least privilege applied to the database layer</strong> — the application gets exactly the access it needs, nothing more.</p><p><strong>What I Learned That Can’t Be Googled</strong></p><p>1. <strong>Read the actual configuration, not just the console UI.</strong> The broken NAT Gateway showed “Active” in the AWS console. Only the CLI revealed the missing subnet association.</p><p>2. <strong>Every layer has its own access control.</strong>Se curity Groups, Network ACLs, OS-level firewall rules, and MySQL user permissions are all separate layers. Fixing one doesn’t fix the others.</p><p>3. “<strong>It looks correct” and “it works” are different things.</strong> The route table pointed to the NAT Gateway. The NAT Gateway appeared active. The path was still broken. Verify end-to-end, not component-by-component.</p><p>4. <strong>Private subnets need NAT to be practical.</strong> You can’t run `apt install` without internet access. NAT Gateway is not a luxury — it’s what makes a private subnet usable.</p><p><strong>The Architecture in Production Context</strong></p><p>What I built this week is the foundation of almost every production web application on AWS. In a real production environment, you’d extend this with:</p><p>- A <strong>Load Balancer</strong> in front of multiple application EC2s (or Auto Scaling groups)</p><p>- <strong>RDS </strong>instead of a self-managed MySQL EC2</p><p>- <strong>Multi-AZ deployments </strong>for high availability</p><p>- <strong>Secrets Manager </strong>for database credentials instead of hardcoded config</p><p>But none of those abstractions make sense until you understand the base: public layer accessible from the internet, private layer accessible only internally, NAT for outbound-only internet from private resources, and security groups as your per-resource firewall.</p><p><strong>Interview Prep That Actually Stuck</strong></p><p>Because I had built and debugged this architecture myself, preparing for technical interviews felt different. When someone asks <em>”How does NAT Gateway work?”</em> — I don’t recall a definition. I remember the moment my private EC2 couldn’t ping 8.8.8.8, and exactly why fixing the NAT Gateway restored connectivity.</p><p>That’s the difference between learning cloud by doing versus learning by reading.</p><p><strong>What’s next: </strong>Three-tier architecture, RDS, Load Balancers, and Auto Scaling. The foundation is solid — now it’s time to build on it.</p><p><em>If you’re on a similar cloud engineering journey, I’d love to connect. Drop a comment or find me on </em><a href="https://www.linkedin.com/in/sankalp-arava-152080170/"><em>LinkedIn</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40eb562dd0f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>