Launching AWS Instance and Deploying Frontend
Episode 13 - Launching AWS Instance and Deploying Frontend
Hey everyone! Welcome back to the Node.js tutorial series. Today we're stepping into the exciting world of cloud computing and REST APIs!
This is where things get REAL - we're going to learn how to deploy our applications to the cloud using AWS!
What we will cover:
- What is AWS?
- What is Cloud Computing Platform?
- Steps to Set Up AWS for Deployment
- What is EC2?
- What is REST API?
- Characteristics of REST API
- HTTP Methods (GET, POST, PUT, PATCH, DELETE)
- Interview Questions
What is AWS?
AWS stands for Amazon Web Services. It is a cloud computing platform that offers a variety of services over the internet.
AWS = Amazon Web Services ========================= - Created by Amazon in 2006 - World's largest cloud platform - Used by Netflix, Airbnb, NASA, and millions more! - Provides 200+ services Services include: - Computing (EC2) - Storage (S3) - Databases (RDS, DynamoDB) - Networking - Machine Learning - And much more!
What is a Cloud Computing Platform?
A cloud computing platform is a network of servers that provide a variety of services such as servers, storage, databases, networking, and so on to users over the internet.
Cloud Computing Platform:
=========================
Instead of this:
----------------
[Your Computer] → Buy expensive servers
→ Set up data center
→ Hire IT team
→ Maintain hardware
→ Pay electricity bills
→ Handle security
Cost: $$$$$$ (Huge upfront investment!)
With Cloud:
-----------
[Your Computer] → Internet → [AWS Cloud]
├── Servers ✓
├── Storage ✓
├── Database ✓
├── Security ✓
└── Everything ✓
Cost: Pay only for what you use!
Key Point: Users can rent access to these services on demand, paying only for what they use!
Cloud Computing Benefits: ========================= 1. No Upfront Cost → Pay as you go 2. Scalability → Scale up/down instantly 3. Reliability → 99.99% uptime 4. Global Reach → Deploy worldwide in minutes 5. Security → Enterprise-grade security 6. No Maintenance → AWS handles hardware
The Restaurant Analogy
Traditional (Own Server): ========================= Like OWNING a restaurant: - Buy the building - Buy all kitchen equipment - Hire all staff - Pay rent even when empty - Handle all repairs Cloud Computing (AWS): ====================== Like RENTING a food court kitchen: - Pay only when cooking - Use professional equipment - Scale up for busy days - No maintenance worries - Cancel anytime!
Steps Involved in Setting Up AWS for Deployment
Let's learn how to deploy our application on AWS step by step!
Step 1: Sign Up in AWS
Step 1: Create AWS Account
==========================
1. Go to aws.amazon.com
2. Click "Create an AWS Account"
3. Enter email and password
4. Provide payment information (credit/debit card)
5. Verify phone number
6. Select support plan (Free tier available!)
Note: AWS Free Tier gives you 12 months of free usage
for many services including EC2!
Step 2: Search for EC2 in Console
Step 2: Navigate to EC2 ======================= 1. Log into AWS Console 2. You'll see the Console Home Page 3. In the search bar at the top, type "EC2" 4. Click on "EC2" from the results AWS Console Home Page: +----------------------------------------+ | [Search bar: "EC2"] | |----------------------------------------| | Recently visited services | | ├── EC2 | | ├── S3 | | └── RDS | +----------------------------------------+
What is EC2?
EC2 stands for Elastic Compute Cloud. It is a web service that allows users to create and run virtual machines, called instances, in the cloud.
EC2 = Elastic Compute Cloud =========================== Think of it as: "Renting a computer in the cloud!" Your Computer EC2 Instance ============ ============= - Physical - Virtual - Limited specs - Choose any specs - One location - Any AWS region - You maintain - AWS maintains EC2 Instance = Virtual Machine (VM) in the cloud
Why "Elastic"?
==============
Because you can:
- Start with small instance (t2.micro)
- Scale up when needed (t2.large)
- Scale down when traffic drops
- Pay only for what you use!
Low Traffic High Traffic
=========== ============
[1 Server] → [10 Servers]
$10/month $100/month
Scale UP and DOWN as needed!
Step 3: Launch Instance
Step 3: Launch Your EC2 Instance ================================ 1. Click on "Launch Instance" button 2. Add a Name to your instance Example: "my-nodejs-app" 3. Select the Operating System (AMI) +----------------------------------+ | Choose an Amazon Machine Image | |----------------------------------| | ○ Amazon Linux 2 | | ● Ubuntu (Preferable!) | | ○ Windows Server | | ○ Red Hat | +----------------------------------+ Ubuntu is recommended for Node.js apps! 4. Select Instance Type +----------------------------------+ | Instance Type | vCPU | Memory | |------------------|------|--------| | t2.micro (Free!) | 1 | 1 GB | | t2.small | 1 | 2 GB | | t2.medium | 2 | 4 GB | +----------------------------------+ Start with t2.micro (Free Tier eligible!)
Step 4: Create a New Key Pair (SSH)
Step 4: Create Key Pair
=======================
1. Click "Create new key pair"
2. Enter key pair name: "my-app-key"
3. Select key pair type: RSA
4. Select format: .pem (for Mac/Linux)
.ppk (for Windows with PuTTY)
5. Click "Create key pair"
6. IMPORTANT: Download and save the .pem file!
This file is like a SECRET KEY to access your instance!
+----------------------------------------+
| ⚠️ WARNING: Save this file safely! |
| |
| - You can only download it ONCE |
| - Without it, you can't access EC2 |
| - Keep it secure (don't share!) |
+----------------------------------------+
What is SSH Key Pair? ===================== Think of it like a house key: Your Key (.pem file) EC2 Instance (House) ==================== ==================== [Private Key] → [Lock that matches] - Only YOUR key can open YOUR instance - No password needed (more secure!) - Never share your private key! To connect via SSH: $ ssh -i "my-app-key.pem" ubuntu@your-ec2-ip
After Instance Launch
What Happens Next? ================== 1. Instance starts (takes 1-2 minutes) 2. You get a Public IP address Example: 54.123.45.67 3. Connect to your instance: $ ssh -i "my-app-key.pem" ubuntu@54.123.45.67 4. Install Node.js on the instance: $ sudo apt update $ sudo apt install nodejs npm 5. Deploy your application: $ git clone your-repo $ cd your-app $ npm install $ npm start Your app is now LIVE on the internet!
Now Let's Talk About APIs!
Before deploying, we need to understand what kind of API our application should have. Let's learn about REST API!
What is REST API?
REST API stands for Representational State Transfer Application Programming Interface. It is a type of API that uses REST architecture to connect applications.
REST API = Representational State Transfer API ============================================== In simple words: "A set of RULES that allows programs to communicate with each other using HTTP requests"
How REST API Works:
===================
Client (Browser/App) Server
==================== ======
"Give me all users"
─────────────────────────→
GET /api/users
←─────────────────────────
[{"name": "John"}, {"name": "Jane"}]
"Add new user"
─────────────────────────→
POST /api/users
{name: "Bob", age: 25}
←─────────────────────────
{"message": "User created!", "id": 3}
REST APIs are commonly used in:
- Client-Server Architecture - Frontend talks to Backend
- Microservices - Services talk to each other
- Web APIs - Third-party integrations
Characteristics of REST API
A good REST API should be:
REST API Characteristics: ========================= 1. Lightweight → Simple and fast 2. Highly Scalable → Handle millions of requests 3. Flexible → Works with any programming language 4. Stateless → No session stored on server 5. Uniform Interface → Standard HTTP methods
Stateless - What Does It Mean?
Stateless:
==========
Each request from client to server must contain
ALL the information needed to process the request.
The server does NOT remember previous requests!
❌ Stateful (BAD):
=================
Request 1: "I am John"
Server: "OK, I'll remember you"
Request 2: "Give me my orders"
Server: "OK John, here are your orders"
(Server remembered who you are)
✅ Stateless (GOOD - REST Way):
==============================
Request 1: "I am John, give me my orders"
{Authorization: "Bearer token123"}
Server: "Here are John's orders"
Request 2: "I am John, update my profile"
{Authorization: "Bearer token123"}
Server: "Profile updated for John"
Every request is INDEPENDENT!
Server treats each request as brand new.
Why Stateless is Better? ======================== 1. Scalability - Any server can handle any request - Easy to add more servers 2. Reliability - Server crash doesn't lose "state" - No session data to manage 3. Simplicity - Easier to understand and debug - Each request is self-contained
Uniform Interface - HTTP Methods
REST APIs use standard HTTP methods to perform operations. This is called a Uniform Interface!
HTTP Methods (CRUD Operations): =============================== ┌──────────┬─────────────────────────────────────────┐ │ Method │ Purpose │ ├──────────┼─────────────────────────────────────────┤ │ GET │ To GET data from the server │ │ POST │ To ADD new data on the server │ │ PUT │ UPDATE the entire doc with the new one │ │ PATCH │ UPDATE only part of the document │ │ DELETE │ To DELETE document from a collection │ └──────────┴─────────────────────────────────────────┘
HTTP Methods Explained
1. GET - Read Data
==================
Request: GET /api/users
Response: [{"id": 1, "name": "John"}, {"id": 2, "name": "Jane"}]
Request: GET /api/users/1
Response: {"id": 1, "name": "John", "age": 25}
- Retrieves data
- Should NOT modify anything
- Safe and idempotent
2. POST - Create Data
=====================
Request: POST /api/users
Body: {"name": "Bob", "age": 30}
Response: {"id": 3, "name": "Bob", "age": 30, "message": "Created!"}
- Creates new resource
- Data sent in request body
- Returns the created resource
3. PUT - Replace Entire Resource
================================
Request: PUT /api/users/1
Body: {"name": "John Updated", "age": 26, "email": "john@new.com"}
Response: {"id": 1, "name": "John Updated", "age": 26, "email": "john@new.com"}
- Replaces the ENTIRE document
- Must send ALL fields
- If field missing, it gets removed!
4. PATCH - Partial Update
=========================
Request: PATCH /api/users/1
Body: {"age": 27}
Response: {"id": 1, "name": "John Updated", "age": 27, "email": "john@new.com"}
- Updates ONLY specified fields
- Other fields remain unchanged
- More efficient for small updates
5. DELETE - Remove Data
=======================
Request: DELETE /api/users/1
Response: {"message": "User deleted successfully"}
- Removes the resource
- Usually returns confirmation
- Idempotent (deleting twice = same result)
PUT vs PATCH - The Key Difference
Original Document:
==================
{
"id": 1,
"name": "John",
"age": 25,
"email": "john@email.com"
}
Using PUT (Replace All):
========================
PUT /api/users/1
Body: {"name": "John", "age": 26}
Result:
{
"id": 1,
"name": "John",
"age": 26
// email is GONE! (not included in PUT)
}
Using PATCH (Update Part):
==========================
PATCH /api/users/1
Body: {"age": 26}
Result:
{
"id": 1,
"name": "John",
"age": 26,
"email": "john@email.com" // Still here!
}
REST API Example with Node.js
const express = require('express');
const app = express();
app.use(express.json());
let users = [
{ id: 1, name: "John", age: 25 },
{ id: 2, name: "Jane", age: 30 }
];
// GET - Get all users
app.get('/api/users', (req, res) => {
res.json(users);
});
// GET - Get single user
app.get('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ error: "Not found" });
res.json(user);
});
// POST - Create new user
app.post('/api/users', (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name,
age: req.body.age
};
users.push(newUser);
res.status(201).json(newUser);
});
// PUT - Replace entire user
app.put('/api/users/:id', (req, res) => {
const index = users.findIndex(u => u.id === parseInt(req.params.id));
if (index === -1) return res.status(404).json({ error: "Not found" });
users[index] = { id: parseInt(req.params.id), ...req.body };
res.json(users[index]);
});
// PATCH - Update part of user
app.patch('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ error: "Not found" });
Object.assign(user, req.body);
res.json(user);
});
// DELETE - Remove user
app.delete('/api/users/:id', (req, res) => {
const index = users.findIndex(u => u.id === parseInt(req.params.id));
if (index === -1) return res.status(404).json({ error: "Not found" });
users.splice(index, 1);
res.json({ message: "User deleted!" });
});
app.listen(3000, () => console.log('Server running on port 3000'));
Quick Recap
| Concept | Description |
|---|---|
| AWS | Amazon Web Services - Cloud computing platform |
| Cloud Computing | Renting servers/services over the internet |
| EC2 | Elastic Compute Cloud - Virtual machines in AWS |
| Key Pair | SSH key to securely connect to EC2 instance |
| REST API | API using REST architecture with HTTP methods |
| Stateless | Each request contains all needed information |
| GET | Retrieve data from server |
| POST | Create new data on server |
| PUT | Replace entire document |
| PATCH | Update part of document |
| DELETE | Remove data from server |
Interview Questions
Q: What is AWS?
"AWS (Amazon Web Services) is a cloud computing platform that offers a variety of services like computing, storage, databases, and networking over the internet. Users can rent these services on demand and pay only for what they use."
Q: What is EC2?
"EC2 stands for Elastic Compute Cloud. It's a web service that allows users to create and run virtual machines (called instances) in the cloud. It's 'elastic' because you can scale up or down based on your needs."
Q: What is a REST API?
"REST API (Representational State Transfer API) is a type of API that uses REST architecture to connect applications. It's a set of rules that allows programs to communicate with each other using HTTP requests. REST APIs are commonly used in client-server architecture and microservices."
Q: What does 'stateless' mean in REST?
"Stateless means each request from client to server must contain all the information needed to process that request. The server doesn't store any client state between requests. This makes APIs more scalable and reliable."
Q: What is the difference between PUT and PATCH?
"PUT replaces the entire resource - you must send all fields, and missing fields will be removed. PATCH updates only the specified fields while keeping other fields unchanged. Use PATCH for partial updates and PUT for complete replacements."
Q: What are the main HTTP methods used in REST APIs?
"The five main HTTP methods are: GET (retrieve data), POST (create new data), PUT (replace entire resource), PATCH (partial update), and DELETE (remove data). These correspond to CRUD operations - Create, Read, Update, Delete."
Key Points to Remember
- AWS is Amazon's cloud computing platform
- Cloud computing = renting servers over internet
- EC2 = Elastic Compute Cloud (virtual machines)
- Key pair is used to securely SSH into EC2
- Choose Ubuntu as OS for Node.js apps
- t2.micro is free tier eligible
- REST API uses HTTP methods to communicate
- Stateless = each request is independent
- GET = Read, POST = Create
- PUT = Replace all, PATCH = Update part
- DELETE = Remove resource
- REST APIs should be lightweight, scalable, flexible
What's Next?
Now you understand AWS basics and REST API concepts! In the upcoming episodes, we will:
- Build a complete REST API with Express.js
- Connect our API to MongoDB
- Deploy our full-stack application to AWS
- Set up CI/CD pipelines
Keep coding, keep learning! See you in the next one!
Post a Comment