Skip to content

Deploy Node API and reverse proxy

Configuring Nginx as a Reverse Proxy

1. Create a small express app

  1. Install nodejs and npm on ubuntu

    Terminal window
    sudo apt install nodejs
    sudo apt install npm
  2. Create a project dir and initialize a node app

    Terminal window
    mkdir express-app
    cd express-app
    npm init -y
  3. Install basic dependencies

    Terminal window
    npm install express nodemon
  4. 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"
    }
    }
  5. Create an `index.js1 file and add the following code

    Terminal window
    touch index.js
    import 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"));
  6. Install pm2 to run this dummy app in the background

    Terminal window
    npm install -g pm2 # if npm is not available use sudo npm install -g pm2
  7. 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.

  1. Edit your server block configuration:

    Terminal window
    sudo vim /etc/nginx/sites-available/default
  2. Configure the server block to act as a reverse proxy:

    server {
    listen 80; # Listen on port 80 for incoming HTTP requests
    server_name localhost; # Server name or domain name this block will respond to
    location / {
    proxy_pass http://127.0.0.1:8080; # Proxy requests to the backend server running on localhost:8080
    proxy_set_header Host $host; # Set the Host header to the client's original host
    proxy_set_header X-Real-IP $remote_addr; # Set the X-Real-IP header to the client's IP address
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # Append client's IP addresses to X-Forwarded-For header
    proxy_set_header X-Forwarded-Proto $scheme; # Set the X-Forwarded-Proto header to the client's protocol (http or https)
    }
    }
  3. Test and reload Nginx:

    Terminal window
    sudo nginx -t
    sudo systemctl reload nginx

Now, when you request http://<server_ip>/api it will return the following response:

{ "message": "server working" }