Codetard
Codetard

Reputation: 2605

Binding a Node.js Application on a Port with Nginx

I'm trying to set a Node.js Application for Production on a Port with SSL on Nginx Ubuntu 17.04. So far I have SSL Nginx server up and running.

This is how my Nginx Configuration file looks like:

server {
listen 80 default_server;
listen [::]:80 default_server;
listen 443 ssl;

root /var/www/html;
index index.php index.html index.htm index.nginx-debian.html;

server_name example.com www.example.com;

location / {
    try_files $uri $uri/ =404;
}

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}

location ~ /\.ht {
    deny all;
}
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot

if ($scheme != "https") {
    return 301 https://$host$request_uri;
} 

    ssl_dhparam /etc/ssl/certs/dhparam.pem;

}

This is how my Node.js Application looks lik:

#content of index.js    
'use strict';

const http = require('http');
http.createServer((req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/html; charset=utf-8',
  });
  res.write('<h1>I’m a Node app!</h1>');
  res.end(3000, 'localhost')
}).listen();
console.log('http://example.com:3000/');

I would want to know how can I bind this Node.js Application on a Port with SSL with the existing Nginx configurations.

Upvotes: 2

Views: 2370

Answers (2)

Codetard
Codetard

Reputation: 2605

Here's my answer to question. There were two mistakes:

1) Edit and addition to server closure file:

location ~ ^/(nodeApp|socket\.io) {
   proxy_pass http://localhost:3000;
}

SocketIO uses /socket.io path by default, so one need to configure Nginx so that it will proxy not only /nodeApp request, but /socket.io too

2) One more edit in Node.js server file. Replace:

http.createServer((req, res) => {` to `app.get('/node', function(req, res) {

Upvotes: 1

Root
Root

Reputation: 185

You have to use nginx as a reverse proxy to your nodejs application.

For example, make node run on port 3000, and do something like this in your nginx conf.

If the node app is the only thing in the server,

server {
   listen 443;
   <-- snip -->

   location / {
      proxy_pass http://localhost:3000;
   }

   <-- snip -->
}

If you have something else like a php application running on the server, create another server block and give a separate server_name for your app.

server {
   listen 443;
   server_name nodeapp.mysite.com;
   <-- snip -->

   location / {
      proxy_pass http://localhost:3000;
   }

   <-- snip -->
}

Upvotes: 1

Related Questions