Monday 28 September 2020

Digitalocean deploying node https app with nginx

I am running my application in a Digitalocean droplet using nginx i have found out that if i run my app with http it works perfectly, but when i run it with https nginx gives me 502 BAD GATEWAY, i have tried other digitalocean guides and searched around stackoverflow and never found the solution so i thought about making this post.

NGINX DEFAULT FILE:

server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;

        server_name mydomain.io www.mydomain.io;

        ssl_certificate /home/myapp/ssl/myapp.crt;
        ssl_certificate_key /home/myapp/ssl/myapp.key;

        location / {
                proxy_pass http://localhost:3000;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }
}

MY APP CODE:

const express = require("express");
//const http = require('http');
const https = require('https');
const helmet = require("helmet");
const cors = require("cors");
const fs = require("fs");
const path = require("path");
const app = express();
const config = require("./config");
const passport = require("passport");
const credentials = { key: fs.readFileSync('ssl/myapp.key', 'utf-8'), cert: fs.readFileSync('ssl/myapp.crt', 'utf-8'), ca: fs.readFileSync('ssl/myapp.ca-bundle', 'utf-8') };

app.use(helmet());
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(
  require("express-session")({
    secret: require("./config.json").app.secretKey,
    resave: false,
    saveUninitialized: true,
    cookie: {
      secure: false,
      maxAge: 60 * 60 * 1000 * 24 * 365,
    },
  })
);

app.use(passport.initialize());
app.use(passport.session());
passport.use(require("./service/passport"));

app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use(express.static(path.join(__dirname, "views")));

app.use('/', require('./api/home'));
app.use("/auth", require("./api/auth"));
app.use("/user", require("./api/user"));

app.get('/tos',(req,res)=>{
  res.render('tos');
});


//var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);

httpsServer.listen(config.app.port,'localhost',()=>{
        console.log("App started on port:"+config.app.port);
});

I am new to nginx can someone explain how to do this?



from Digitalocean deploying node https app with nginx

No comments:

Post a Comment