Listen for HTTPS requests to port 3000 on EC2 for nodejs express app

I have a nodejs app that uses express to listen on 3000 for requests like so:

var express = require('express');
var app = express();
app.listen(3000, function () {
   console.log('Running on port 3000')
});

This works for HTTPS requests when I run the server locally with ngrok. But when running the nodejs app on EC2 I cannot hit this port through HTTPS. I have the security group for my instance setup as follows:

enter image description here

I can hit port 3000 on plain HTTP but not HTTPS, anyone know where I'm going wrong?

Answers:

Answer

MattTheHack, by default I believe Express listens via an HTTP Server. There are two things you can do here, the first being deploying your node express app as an HTTPS server, which requires the proper keys to get set up.

Something like the following:

var express = require('express')
var fs = require('fs')
var https = require('https')
var app = express()

app.get('/', function (req, res) {
  res.send('hello world')
})

https.createServer({
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.cert')
}, app)
.listen(3000, function () {
  console.log('Example app listening on port 3000! Go to https://localhost:3000/')
})

This is not really recommended because then node is decrypting all the HTTPS traffic.

The recommended solution would be to place NGINX or some other routing tool on the server as well. You can then treat NGINX as a Proxy and allow NGINX to do the decryption for you. Your node app can still listen to port 3000 as an HTTP server, and NGINX simply redirects HTTPS port 443 traffic to localhost:3000

nginx.conf

http {
  server {
    listen 443 ssl;
    ssl_certificate      "PATH_TO_CERT";
    ssl_certificate_key  "PATH_TO_CERT_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;
    }
  }
}

I would definitely recommend the second approach! Good luck!

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.