Setting the port for node.js server on Heroku

拈花ヽ惹草 提交于 2019-11-27 06:34:14

问题


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 should either read the PORT env variable or default to 8080, as it does when it's run locally. Neither of them is happening on Heroku, and the server always uses the default port 80. Any idea how to change it?

heroku config
PORT: 8080

回答1:


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




回答2:


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




回答3:


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




回答4:


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




回答5:


You can do for example:

const PORT = process.env.PORT || 5001;

app.listen(PORT, () => console.log(`Server is listening on port ${PORT}...`));


来源:https://stackoverflow.com/questions/28706180/setting-the-port-for-node-js-server-on-heroku

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!