Nginx – How to connect node.js backend to NGINX reverse proxy server

nginxnode.js

I know I'm close but I can't seem to connect my node.js app to my NGINX reverse proxy. My node app works locally and my config file tests ok. It doesn't connect after it's been uploaded to Digital Ocean.

The error is 502 Bad Gateway.

Something is missing and after a couple of hours of googling and testing I still can't find the problem. Thanks so much for any help in advance!

These are the relevant lines from my nginx.conf file.

 server {
        listen        80;
        listen        [::]:80;
        server_name   myDomainName.com;
        root          /www/html;

        location / {
             index       index.html;
        }

        location /proxytest {
            proxy_pass "http://www.myDomainName.com:8080";
        }

    }

This is my node.js test app.

const express = require('express');

const app = express();

app.get('/', (request, response) => {
    response.send('Hello World!');
});

app.listen(8080, () => {
    console.log('Server is up on port 8080');
});

Best Answer

If this is all running a single instance, then typically Nginx wants to talk to a local nodejs service running on port 8080, and so localhost would be more usual than www.myDomainName.com

This would normally be something like

 location /proxytest {
            proxy_pass http://localhost:8080;
        }

Whatever you set the proxy_pass value to, you should check that address is available from the nginx box command line.

# curl -I  http://localhost:8080
HTTP/1.1 200 OK
X-Powered-By: Express
Date: Tue, 06 Feb 2018 02:23:35 GMT
Connection: keep-alive

Also you can check the error log on nginx to see if it reported anything funny.

vi /var/log/nginx/error.log

Other things to try

If you are on an selinux distribution (CentOS, Fedora, RHEL...) try disabling selinux and try the request again

 # setenforce Permissive
 setenforce: SELinux is disabled