How to run nodejs server over 443 ensuring nginx d

2019-03-04 03:46发布

问题:

My Nginx default file looks like this:

server {
       listen  80;
       server_name humanfox.com www.humanfox.com;
       rewrite  ^/(.*)$ https://www.humanfox.com$1 permanent;
}


server {
        listen 443 ssl spdy;
        server_name humanfox.com www.humanfox.com;
        ssl on;
        ssl_certificate /root/ca3/www.humanfox.com.crt;
        ssl_certificate_key /root/ca3/humanfox.com.key;
        access_log  /var/log/nginx/humanfox.com.access.log;
        error_log   /var/log/nginx/humanfox.com.error.log;
        rewrite     ^/(.*)$ https://www.humanfox.com$1 permanent;
}

Now, Nginx is running properly but when I try to run my nodejs server on port 443(https) it says EADDR already in use. When I kill the port to use my nodejs server instead, it also kills Nginx and Nginx stops working.

How do I run my nodejs server on 443 ensuring nginx doesn't close.

回答1:

You can't run nodejs on port 443 and nginx to serve ssl(443) at the same time. You can do this by configuring nginx as a reverse proxy for nodejs.

Let say you are running nodejs in port 3000.

const http = require('http');
http.createServer((req,res) => {
  res.writeHead(200, {"Content-Type":"plain/html"});
  res.end('Node is Running');
}).listen(3000);

your nginx config should be:

server {
    listen 443 ssl spdy;

    server_name humanfox.com www.humanfox.com;
    ssl on;
    ssl_certificate /root/ca3/www.humanfox.com.crt;
    ssl_certificate_key /root/ca3/humanfox.com.key;
    access_log  /var/log/nginx/humanfox.com.access.log;
    error_log   /var/log/nginx/humanfox.com.error.log;

    location / {
        proxy_set_header X-Forwarder-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;
        proxy_redirect off;
    }
}

Hope it Helps.



回答2:

You will not be able listen on the same port as nginx is already listening on.

What you can do is listen on some different port and configure nginx as a reverse proxy to connect to your node process. That way from the point of view of external users it will look exactly how you want - the Node app will be accessible on the 443 port - but there would be no conflict of ports.

See this answers for examples on how to do that:

  • Where do I put my Node JS app so it is accessible via the main website?
  • How do I get the server_name in nginx to use as a server variable in node
  • Configuring HTTPS for Express and Nginx


标签: node.js nginx