Deploy Node.js API and Set Up Nginx Reverse Proxy: Your Web Traffic Control Tower! ๐ฆ
Hey there, web architects! ๐ Ready to build your own internet skyscraper? Letโs deploy a Node.js API and set up Nginx as a reverse proxy. Itโs like creating your own web traffic control tower! ๐ข
#Part 1: Building Our Express Skyscraper ๐๏ธ
#Step 1: Get Your Building Materials (Install Node.js and npm) ๐งฑ
First, letโs get our tools ready. Open your terminal and type:
sudo apt install nodejs npm
#Step 2: Create Your Construction Site ๐ง
Letโs make a spot for our new building:
mkdir express-app
cd express-app
npm init -y
#Step 3: Gather More Supplies (Install Dependencies) ๐ ๏ธ
Time to get some special building blocks:
npm install express nodemon
#Step 4: Draw Up the Blueprints (Update package.json) ๐
Open your package.json
and make it look like this:
{
"name": "express-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"dev": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.19.2",
"nodemon": "^3.1.4"
}
}
#Step 5: Build Your Express Elevator (Create index.js) ๐
Create a new file called index.js
and add this code:
import express from "express"
const app = express()
app.get("/api", (req, res) => {
return res.status(200).json({
message: "server working",
})
})
app.listen(5000, () => console.log("Server is running on 5000"))
#Step 6: Hire a Building Manager (Install PM2) ๐ท
PM2 will keep our building running 24/7:
npm install -g pm2
#Step 7: Open for Business! ๐
Start your new skyscraper:
pm2 start "npm run dev"
#Part 2: Setting Up Your Traffic Control Tower (Nginx Reverse Proxy) ๐ผ
#Step 1: Configure Your Control Tower ๐ง
Open your Nginx config file:
sudo nano /etc/nginx/sites-available/default
#Step 2: Program Your Traffic Controller ๐ฆ
Replace the content with this:
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
#Step 3: Test and Launch Your Control Tower ๐
Check if everythingโs okay:
sudo nginx -t
If it says โOKโ, letโs start directing traffic:
sudo systemctl reload nginx
#You Did It! Your Web Skyscraper is Open for Business! ๐
Congratulations, web architect! Youโve just built a high-tech API skyscraper with its own traffic control tower. Now when someone visits http://<your-server-ip>/api
, theyโll get a warm welcome message:
{ "message": "server working" }
Your Express app is now running behind Nginx, protected and ready to handle tons of visitors. Keep building and reaching for the (web) stars! ๐๐๏ธ