Ubuntu + Nginx + NodeJS: 502 Bad Gateway

Viewed 133

Currently I am trying to build a small nodejs API which should work on my server behind an already existing and working nginx setup.

nginx.conf:

server {
    listen 80;
    listen [::]:80;
    server_name *.mydomain.com;

    if ($host = www.mydomain.com) {
        return 301 https://$host$request_uri;
    }

    if ($host = mydomain.com) {
        return 301 https://$host$request_uri;
    }

    if ($host = hello.mydomain.com) {
        return 301 https://$host$request_uri;
    }

    return 404;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name mydomain.com www.mydomain.com;

    root /var/www/html;
    index index.html;

    ssl_certificate /etc/ssl/cert.pem;
    ssl_certificate_key /etc/ssl/key.pem;
    ssl_client_certificate /etc/ssl/cloudflare.crt;
    ssl_verify_client on;

    location / {
        try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name hello.mydomain.com;

    root /var/www/hello;

    ssl_certificate /etc/ssl/cert.pem;
    ssl_certificate_key /etc/ssl/key.pem;
    ssl_client_certificate /etc/ssl/cloudflare.crt;
    ssl_verify_client on;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://127.0.0.1:3000$request_uri;
        proxy_redirect off;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

index.js:

const express = require('express');

const app = express();

app.get("/", (request, response) => {
    response.end("hello world");
});

app.listen(3000, () => console.log('listening'));

So i have mydomain.com and www.mydomain.com and they have nothing to do with nodejs and work fine.

The nodejs site lies behind hello.mydomain.com and just returns a 502: Bad Gateway error. When I am on my server (where everything lies) and just do:

curl localhost:3000

I get the right response. So the nodejs code works (I even approved it locally), but the nginx is not able to act as a proxy and "speak" with the local nodejs express.

Does anyone know why this does not work? I already searched through many tutorials, but I just cannot find the solution. :/

0 Answers
Related