Deploy Node API with Nginx
Prerequisites
Before going forward, make sure you have the following prerequisites:
- A server with root access
- A domain name or IP address
- A web server that can be used to serve static files
- Nginx installed and configured on the machine
- SSL configured for the domain name or IP address
Create a Small Express App
We will create a small express app to test the deployment. Here are the steps:
-
Install
nodejsandnpmon ubuntu
Terminal 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.jsfile 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
pm2to run this dummy app in the background
Terminal 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.
Do a reverse proxy with nginx
Nginx can also act as a reverse proxy, forwarding client requests to other servers. Here are the steps to configure Nginx as a reverse proxy:
-
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>/apiit will return the following response:
{ "message": "server working" }
Summary
In this guide, we learned how to deploy a Node API with Nginx on Ubuntu server. We also learned how to configure Nginx as a reverse proxy.
Start your journey with ChaiCode
All of our courses are available on chaicode.com. Feel free to check them out.