Node.js https server: Can't listen to port 443 - Why?

前端 未结 1 396
醉酒成梦
醉酒成梦 2020-12-29 11:59

I\'m creating a an HTTPS server for the first time in Node, and the code (see below) works for a random port like 6643 but on port 443, it won\'t work. I get this error:

相关标签:
1条回答
  • 2020-12-29 12:19

    On Linux (and, I believe, most other Unix-like operating systems), a service has to run as root to be able to bind to a port numbered less than 1024.

    I've just verified it on a Node app I had lying around, and I saw exactly the same error, line for line identical barring the file paths, when I changed the port from 5000 to 443.

    In development, most people will run the dev server on a higher-numbered port such as 8080. In production, you might well want to use a proper web server such as Nginx to serve static content and reverse proxy everything else to your Node app, which makes it less of an issue since Nginx can be quite happily run as root.

    EDIT: As your use case requires serving some static content, then you may want to use a web server such as Nginx or Apache to handle the static files, and reverse proxy to another port for your dynamic content. Reverse proxying is quite straightforward with Nginx - here's a sample config file:

    server {
        listen 443;
        server_name example.com;
        client_max_body_size 50M;
    
        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;
    
        location /static {
            root /var/www/mysite;
        }
    
        location / {
            proxy_pass http://127.0.0.1:8000;
        }
    }
    

    This assumes your web app is to be accessible on port 443, and is running on port 8000. If the location matches the /static folder, it is served from /var/www/mysite/static. Otherwise, Nginx hands it off to the running application at port 8000, which might be a Node.js app, or a Python one, or whatever.

    This also quite neatly solves your issue since the application will be accessible on port 443, without having to actually bind to that port.

    It should be said that as a general rule of thumb running a service like this as root isn't a good idea. You'd be giving root access to an application which might potentially have vulnerabilities, and to any NPM modules you've pulled in. Putting it behind, for example, Nginx will mean you don't need to run it as root, and Nginx is solid and well-tested, as well as having solid performance and caching capability. In addition, Nginx will usually be faster at serving static content in particular.

    0 讨论(0)
提交回复
热议问题