Creating a Server | node js
Episode 11 - Creating a Server
Hey everyone! Welcome back to the Node.js tutorial series. Today we are going to learn about Creating a Server!
This is where you'll understand the fundamentals of how servers work and how to create your own HTTP server in Node.js.
What we will cover:
- What is a Server?
- Hardware vs Software Server
- AWS and Cloud Computing
- Client-Server Architecture
- Sockets and TCP/IP Protocol
- Protocols (HTTP, FTP, SMTP)
- DNS (Domain Name System)
- Ports and Multiple Servers
- Distributed Server Architecture
- Socket vs WebSockets
Q: What is a Server?
The term "server" can refer to both hardware and software, depending on the context.
Hardware: A physical machine (computer) that provides resources and services to other computers (clients) over a network.
Software: An application or program that handles requests and delivers data to clients.
Server - Two Meanings: ====================== 1. HARDWARE SERVER ┌─────────────────────┐ │ Physical Machine │ │ - CPU │ │ - RAM │ │ - Storage │ │ - Network Card │ └─────────────────────┘ 2. SOFTWARE SERVER ┌─────────────────────┐ │ Application that │ │ handles requests │ │ - HTTP Server │ │ - Database Server │ │ - File Server │ └─────────────────────┘
Deploying an Application on a Server
When someone says "deploy your app on a server," they usually mean:
- Hardware Aspect: You need a physical machine (server) to run your application. This machine has a CPU, RAM, storage, etc.
- Operating System (OS): The server hardware runs an operating system like Linux or Windows. Your application runs on this OS.
- Server Software: The software (e.g., a web server like Apache or an application server built with Node.js) that handles requests from users.
Deployment Stack: ================= ┌─────────────────────────┐ │ Your Application │ ← Node.js app ├─────────────────────────┤ │ Server Software │ ← HTTP Server ├─────────────────────────┤ │ Operating System │ ← Linux/Windows ├─────────────────────────┤ │ Hardware (Server) │ ← CPU, RAM, Storage └─────────────────────────┘
AWS and Cloud Computing
AWS (Amazon Web Services) provides cloud-based resources, including servers.
EC2 Instance: When you launch an EC2 instance, you're essentially renting a virtual server from AWS. AWS manages the underlying hardware, and you deploy your application on the virtual server.
Benefits of AWS:
- Scalability: AWS allows you to easily scale your resources. You can increase the memory or processing power of your server with a few clicks, which is not as straightforward on a physical laptop.
- Reliability: AWS servers are equipped with constant power, internet backup, and redundant systems to ensure high availability.
Q: Can You Use Your Own Laptop as a Server?
A: Yes, but with limitations!
- Hardware Constraints: Your laptop likely has limited RAM, CPU, and storage, which may not be sufficient for handling a large number of requests.
- Internet Connectivity: A home internet connection is typically less reliable and has dynamic IP addresses, making it less suitable for hosting a publicly accessible server.
- Power and Maintenance: Ensuring that your laptop is always on, connected to the internet, and has backup power is challenging. AWS handles all these concerns for you.
Laptop vs Cloud Server: ======================= Your Laptop: - Limited RAM/CPU - Dynamic IP address - No power backup - Must stay ON 24/7 - Limited bandwidth AWS EC2: - Scalable resources - Static IP address - Power backup - 99.9% uptime - High bandwidth
Client-Server Architecture
The term "client" refers to someone accessing a server. Imagine a user sitting at a computer wanting to access a file from a server.
Client-Server Model:
====================
CLIENT SERVER
┌─────────────┐ ┌─────────────┐
│ Browser │ ──Request──→ │ HTTP │
│ (User) │ │ Server │
│ │ ←Response── │ │
│ IP: x.x.x.x│ │ IP: y.y.y.y │
└─────────────┘ └─────────────┘
Both have IP addresses!
Communication happens through SOCKETS
For this, the client needs to open a socket connection (not to be confused with WebSocket). Every client has an IP address, and every server has an IP address as well.
To access the file, the client opens a socket connection. On the server side, there should be an application that is listening for such requests, retrieves the requested file, and sends it back to the client.
Multiple Clients and Socket Connections
There can be multiple clients, and each client creates a socket connection to get data. After the data is received, the socket connection is closed. If the client needs to make another request, a new socket connection is created, data is retrieved, and the connection is closed again.
Multiple Client Connections: ============================ Client 1 ──Socket──→ ┌─────────┐ Client 2 ──Socket──→ │ SERVER │ Client 3 ──Socket──→ │ │ Client 4 ──Socket──→ └─────────┘ Each socket: 1. Opens connection 2. Sends request 3. Receives response 4. Closes connection
Sockets operate using the TCP/IP protocol (Transmission Control Protocol/Internet Protocol).
What is a Protocol?
A protocol is a set of rules that define how computers communicate with each other. Protocols determine the format in which data is sent between devices.
- FTP (File Transfer Protocol): Used for transferring files
- SMTP (Simple Mail Transfer Protocol): Used for sending emails
- HTTP (HyperText Transfer Protocol): Used for web communication
- TCP/IP: Foundation protocol for internet communication
Common Protocols: ================= HTTP → Web pages, APIs HTTPS → Secure web communication FTP → File transfers SMTP → Sending emails POP3 → Receiving emails SSH → Secure shell access
When we talk about a web server, we usually mean an HTTP server. HTTP (HyperText Transfer Protocol) is a language or set of rules that defines how clients and servers communicate.
Q: When you make a server request, how is data sent?
A: Data is sent in chunks, and these smaller units are known as packets!
Whenever data is transmitted, it's broken down into these packets. The TCP/IP protocol is responsible for sending these packets and ensuring that the data transmission is properly managed.
Data Transmission:
==================
Large Data (e.g., Video)
│
▼
┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐
│ P1│ │ P2│ │ P3│ │ P4│ │ P5│ ← Packets
└───┘ └───┘ └───┘ └───┘ └───┘
│
TCP/IP sends packets
│
▼
Client receives
and reassembles
In Node.js, there are concepts of streams and buffers that are used for handling and writing code related to data transmission.
Domain Names and DNS
We don't generally communicate using IP addresses; instead, we use domain names like youtube.com. However, at the end of the day, everything maps to an IP address.
As humans, we don't easily understand or remember IPs, similar to how we save contacts with names instead of memorizing phone numbers.
Domain Name vs IP: ================== What you type: youtube.com What it maps to: 142.250.190.46 Just like: Contact name: "Mom" Phone number: +1-555-123-4567
When we request a URL like youtube.com, internally, it is translated into an IP address. This is where the Domain Name System (DNS) comes into play.
A DNS server manages the mapping between domain names and IP addresses. When you request a website, your browser calls a DNS server to resolve the domain name into an IP address. Once the IP is resolved, a call is made to the server.
DNS Resolution Process: ======================= 1. User types: youtube.com 2. Browser asks DNS: "What's the IP for youtube.com?" 3. DNS responds: "142.250.190.46" 4. Browser connects to 142.250.190.46 5. Server sends back the webpage User → DNS → Server → User
As a user, you don't see what happens behind the scenes. When you request an IP, it goes to the server where an HTTP server processes the request and sends back the data. This data is sent in chunks, known as streams, and the process involves buffers, which is why you sometimes see the video buffering.
Q: Can I create multiple servers?
A: Yes, you can create multiple HTTP servers!
Now, suppose a user is sending a request. How do we know which server it should go to?
When creating multiple HTTP servers, it means we are setting up different Node.js applications. The distinction between these servers is defined by a port, which is typically a 4-digit number (e.g., port 3000).
Multiple Servers with Ports: ============================ IP Address: 102.209.1.3 ┌─────────────────────────────────────────┐ │ Single Computer │ │ │ │ ┌─────────────┐ ┌─────────────┐ │ │ │ App 1 │ │ App 2 │ │ │ │ Port: 3000 │ │ Port: 3001 │ │ │ │ (React) │ │ (Node.js) │ │ │ └─────────────┘ └─────────────┘ │ │ │ └─────────────────────────────────────────┘ 102.209.1.3:3000 → React App 102.209.1.3:3001 → Node.js App
For example, suppose an HTTP server with IP address 102.209.1.3 is running on port 3000. This combination of IP address and port number (102.209.1.3:3000) indicates which specific HTTP server the request should be routed to.
Mapping Domain Names, IPs, Ports, and Paths
When you enter a domain name like youtube.com, it gets mapped to an IP address by a DNS server. The IP address identifies the specific server where the website is hosted.
Now, when you combine the IP address with a port number, you can direct the request to a specific application running on that server.
If you add a path to the URL, you can create specific API routes:
- youtube.com → React application on port 3000
- youtube.com/api/... → Node.js application on port 3001
URL Mapping Example: ==================== namastedev.com Setup: --------------------- React App → Port 3000 Node.js App → Port 3001 namastedev.com → React App (Port 3000) namastedev.com/node → Node.js App (Port 3001) namastedev.com/api → API Routes (Port 3001) This is how you manage multiple apps on same server!
Distributed Server Architecture
In large companies, the architecture is often distributed across multiple servers rather than relying on a single server. This approach helps manage different aspects of the application efficiently and ensures scalability, reliability, and performance.
1. Separation of Concerns
Frontend Server: This server handles the user interface (UI) of the application. It serves the HTML, CSS, and JavaScript files that the browser needs to render the website.
Backend Server: This server processes the logic, handles requests, and interacts with the database.
2. Dedicated Database Server
The database is typically hosted on a separate, powerful server that is optimized for storing and managing data.
3. Media and File Servers
Large files like videos, images, and other media are often stored on specialized servers. These servers are optimized for handling large amounts of data and delivering it quickly.
Distributed Architecture Example:
=================================
namastedev.com Architecture:
┌──────────────┐ ┌──────────────┐
│ Frontend │ │ Backend │
│ Server │────→│ Server │
│ (React) │ │ (Node.js) │
└──────────────┘ └──────┬───────┘
│
┌─────────────┼─────────────┐
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Database │ │ Video │ │ Image │
│ Server │ │ Server │ │ Server │
│ (MongoDB)│ │ (CDN) │ │ (CDN) │
└──────────┘ └──────────┘ └──────────┘
4. Inter-Server Communication
When a client makes a request, the frontend or backend server might need to communicate with other servers to get the necessary data.
For example, if you request a video on namastedev.com, the server might make an API call to another server that hosts the video content, retrieve it, and then send it to the client.
This distributed approach helps large companies manage massive amounts of data and traffic efficiently, ensuring that users have a smooth and responsive experience.
Socket vs WebSockets
When a user makes a request to a website, a socket connection is established between the client and the server.
Regular Socket (HTTP): ====================== Client Server │ │ │──Open Connection───────→│ │ │ │──Send Request──────────→│ │ │ │←─Receive Response───────│ │ │ │──Close Connection───────│ │ │ New request = New connection (overhead!)
This connection is typically used for a single request-response cycle: the client sends a request, the server processes it, sends back the response, and then the socket is closed.
WebSockets introduce a more efficient approach:
WebSocket: ========== Client Server │ │ │──Open Connection───────→│ │ │ │←──────────────────────→│ Bi-directional │←──────────────────────→│ communication! │←──────────────────────→│ │ │ │ Connection stays OPEN │ │ │ Real-time communication! Used for: Chat apps, Live updates, Gaming
Key Differences:
| Socket (HTTP) | WebSocket |
|---|---|
| Opens and closes for each request | Stays open continuously |
| Client initiates requests | Server can push data anytime |
| Good for static content | Good for real-time apps |
| Higher overhead | More efficient for frequent updates |
Creating an HTTP Server in Node.js
Now let's create a simple HTTP server!
const http = require('http');
// Create HTTP server
const server = http.createServer((req, res) => {
// req = request object (what client sends)
// res = response object (what we send back)
console.log("Request received!");
console.log("URL:", req.url);
console.log("Method:", req.method);
// Set response header
res.writeHead(200, { 'Content-Type': 'text/plain' });
// Send response
res.end('Hello from Node.js Server!');
});
// Start listening on port 3000
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
node server.js
OUTPUT: Server running at http://localhost:3000/ // When you visit http://localhost:3000 in browser: Request received! URL: / Method: GET
Quick Recap
| Concept | Description |
|---|---|
| Server | Hardware (machine) or Software (application) |
| Client | User/browser making requests |
| Socket | Connection between client and server |
| Protocol | Rules for communication (HTTP, FTP, etc.) |
| DNS | Maps domain names to IP addresses |
| Port | Identifies specific application on server |
| Packets | Small chunks of data sent over network |
Interview Questions
Q: What is a server?
"A server can refer to hardware (a physical machine) or software (an application that handles requests). In web development, we usually mean an HTTP server that listens for client requests and sends back responses."
Q: What is the difference between Socket and WebSocket?
"Regular sockets open a connection for each request-response cycle and then close. WebSockets maintain a persistent connection, allowing bi-directional real-time communication between client and server."
Q: What is DNS?
"DNS (Domain Name System) is like a phonebook for the internet. It translates human-readable domain names (like google.com) into IP addresses that computers use to identify each other on the network."
Q: What is a port and why is it needed?
"A port is a number that identifies a specific application on a server. Since a server can run multiple applications, ports help direct incoming requests to the correct application. For example, port 3000 for React, port 3001 for Node.js API."
Key Points to Remember
- Server = Hardware OR Software
- Socket = Connection between client and server
- TCP/IP = Protocol for data transmission
- Packets = Small chunks of data
- DNS = Domain to IP mapping
- Port = Identifies specific application
- HTTP = Protocol for web communication
- Data sent as streams and buffers
- WebSockets for real-time communication
- Large companies use distributed architecture
What's Next?
Now you understand the fundamentals of servers! In the next episode, we will:
- Create a full HTTP server
- Handle different routes
- Build REST APIs
Keep coding, keep learning! See you in the next one!
Post a Comment