简体   繁体   中英

How do ports work in Node.js when on the server?

I'm currently developing a node server locally, and to access it I have the server listen on 8080 and then go to localhost:8080 in the browser. However, how will ports work when I put this project on the internet?

How it works once you "put it on the internet" will be exactly the same. The browser still makes a request to a port (most likely 80 or 443 on the internet), except it will likely be going to a webserver via the internet instead of localhost .

If you want to learn about deploying a node project to a server check out this guide . Basically you need to setup a proxy to sit in front of node to handle all the server stuff like requests and ssl certificates.

I am assuming you mean serve your node.js program and proxy your localhost port to Internet by put this project on the internet . A short answer is that you never host your API on some port on Internet but exposure your local port to a Internet port.

I believe you already know someway to serve a node.js program stably. If not, I really recommend pm2 .

If you want to exposure your API to Internet, you first have to get an IP for your local network so that other people can reach your network by this IP. You can also relate it to a domain. Then use softwares like IPfire to manage port mapping. For example, you can map yourIP:8080 to IP ofLocalhostAtLocalNetwork:8080 . Then, people can reach your API through yourIP:8080 . Or you can simply map yourIP:80 to IPofLocalhostAtLocalNetwork:8080 so that people can reach your API directly by your IP.

Another very popular tool to server and proxy services is nginx . With Nginx, you can easily serve some services and proxy whatever port to whatever service.

You will need to access the global variable " process.env " to dynamically determine the port number when your code is running from a server. The process.env property returns an object containing the user environment.

You may do something like the following to cater to both local and server environments dynamically:

//set port and ip
app.set("port", process.env.PORT || 8080);
app.set("ip", process.env.IP || "0.0.0.0");

app.listen(app.get("port"), app.get("ip"), function (err) {
    if (err) {
        console.error(err);
        return;
    } else {
        console.info("cicak is running on port " + app.get("port") + ".");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM