Deploy Node API and reverse proxy
Configuring Nginx as a Reverse Proxy
1. Create a small express app
-
Install
nodejs
andnpm
on ubuntuTerminal window sudo apt install nodejssudo apt install npm -
Create a project dir and initialize a node app
Terminal window mkdir express-appcd express-appnpm init -y -
Install basic dependencies
Terminal window npm install express nodemon -
Update the
package.json
{"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"}} -
Create an `index.js1 file and add the following code
Terminal window touch index.jsimport express from "express";const app = express();app.get("/api", (req, res) => {return res.status(200).json({message: "server working",});});app.listen(8080, () => console.log("Server is running on 8080")); -
Install
pm2
to run this dummy app in the backgroundTerminal window npm install -g pm2 # if npm is not available use sudo npm install -g pm2 -
Run the application with the following command:
Terminal window pm2 start "npm run dev"
This will start the application on port 8080
.
2. Do a reverse proxy with nginx
Nginx can also act as a reverse proxy, forwarding client requests to other servers.
-
Edit your server block configuration:
Terminal window sudo vim /etc/nginx/sites-available/default -
Configure the server block to act as a reverse proxy:
server {listen 80; # Listen on port 80 for incoming HTTP requestsserver_name localhost; # Server name or domain name this block will respond tolocation / {proxy_pass http://127.0.0.1:8080; # Proxy requests to the backend server running on localhost:8080proxy_set_header Host $host; # Set the Host header to the client's original hostproxy_set_header X-Real-IP $remote_addr; # Set the X-Real-IP header to the client's IP addressproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # Append client's IP addresses to X-Forwarded-For headerproxy_set_header X-Forwarded-Proto $scheme; # Set the X-Forwarded-Proto header to the client's protocol (http or https)}} -
Test and reload Nginx:
Terminal window sudo nginx -tsudo systemctl reload nginx
Now, when you request http://<server_ip>/api
it will return the following response:
{ "message": "server working" }