Setting the port for node.js server on Heroku

前端 未结 6 1331
醉梦人生
醉梦人生 2020-11-30 09:51

I launched a node.js server with the following line to set the port:

app.set(\'port\', process.env.PORT || 8080);

This means that, it shoul

相关标签:
6条回答
  • 2020-11-30 10:07

    All the answers are great! Wanted to touch on the theory a bit so people can understand why Heroku sets it port to 80 or 443.

    Computers had to create a convention to communicate with each other with a different protocol. For example HTTP, HTTPS, SSH, FTP , etc.

    As a result, there was an agreement that computers will communicate HTTP with port 80, https will communicate on port 443, and so on with the other protocol. Below is a table displaying all the protocol's conventional reserve port number.

    Now some of you guys may be thinking well if these are reserve port number how come my computer lets me use port number 80 and 443 (ex localhost:80). You can use any port number (in fact you can choose up to 65,535 port number) but once you want to deploy to live and want others to use your application then you will have to start using the convention of port 80 (HTTP) or port 443 (https).

    Heroku makes it nice and easy for you by providing an environment variable process.env.PORT to apply for the correct conventional port number so others can access your app.

    0 讨论(0)
  • 2020-11-30 10:08

    You can do for example:

    const PORT = process.env.PORT || 5001;
    
    app.listen(PORT, () => console.log(`Server is listening on port ${PORT}...`));
    
    0 讨论(0)
  • 2020-11-30 10:11

    In my case, heroku was listening on the default HTTPS port: 443 and it was not visible via heroku config:get PORT.

    0 讨论(0)
  • 2020-11-30 10:15

    You should use the port opened by heroku like so:

    port = process.env.PORT || 80
    

    It sets the port to 80 if it has somehow not been set already

    0 讨论(0)
  • 2020-11-30 10:17

    Heroku treats web apps just like any other app and doesn't allow you to assign listening ports directly. Your web server will be assigned a dynamic port by Heroku but to ACCESS it, you will need to use the default port (80).

    On Heroku, apps are completely self-contained and do not rely on runtime injection of a webserver into the execution environment to create a web-facing service. Each web process simply binds to a port, and listens for requests coming in on that port. The port to bind to is assigned by Heroku as the PORT environment variable.

    The contract with Heroku is for the process to bind to a port to serve requests. Heroku’s routers are then responsible for directing HTTP requests to the process on the right port.

    Reference: Heroku Runtime Principles - Web Servers

    0 讨论(0)
  • 2020-11-30 10:21

    You can't. Heroku sets the PORT variable that you are supposed to bind, and listens on tcp/80.

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