nginx, node.js,

Setup Nginx proxy for a Node.js app

Oct 22, 2021 · 1 min read · Post a comment

Behind every major player in the cloud provider’s field, there is a hidden “magic” that makes our applications work. Most of the time, this magic is some kind of proxy, mostly Nginx. But, how about we get our hands dirty and setup an Nginx proxy for a Node.js app, on our own server.

Prerequisites

  • Nginx
  • Node.js
  • sudo privileges

Solution

Step 1. Create an Nginx conf file for the Node.js app.

touch /etc/nginx/conf.d/nodejsapp.conf

Step 2. Open the file with your favorite code editor, nano, Vim, whatever, and paste the following configuration:

upstream nodejsapp_upstream {
    server 127.0.0.1:5000;
}

server {
    listen 80;
    server_name nodejsapp.yourdomain;

    location / {
        proxy_set_header X-Forwarded-For $remote_addr;
    	proxy_set_header Host $http_host;
    	proxy_pass http://nodejsapp_upstream;
    }
}

Step 3. Save the file and test the Nginx configuration.

nginx -t

Expected output:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Step 4. Reload or restart Nginx.

sudo systemctl reload nginx
or
sudo systemctl restart nginx

Step 5. Now, test the proxy by opening a web browser or run curl and try to reach the domain URL defined in the Nginx config above.

Conclusion

If you want to integrate the Nginx proxy with the famous PM2 daemon process manager, they have a great Nginx production configuration setup example here. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.