在 Heroku 上设置 node.js 服务器的端口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28706180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting the port for node.js server on Heroku
提问by Crocodile
I launched a node.js server with the following line to set the port:
我使用以下行启动了一个 node.js 服务器来设置端口:
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?
这意味着,它应该读取 PORT 环境变量或默认为 8080,就像它在本地运行时一样。Heroku 上没有发生它们,服务器总是使用默认端口 80。知道如何更改它吗?
heroku config
PORT: 8080
回答by punund
You can't. Heroku sets the PORT variable that you are supposed to bind, and listens on tcp/80.
你不能。Heroku 设置您应该绑定的 PORT 变量,并侦听 tcp/80。
回答by QW3RTY
You should use the port opened by heroku like so:
您应该像这样使用由 heroku 打开的端口:
port = process.env.PORT || 80
It sets the port to 80 if it has somehow not been set already
如果尚未设置端口,则将端口设置为 80
回答by gomisha
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).
Heroku 像对待任何其他应用程序一样对待 Web 应用程序,并且不允许您直接分配侦听端口。Heroku 将为您的 Web 服务器分配一个动态端口,但要访问它,您需要使用默认端口 (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.
在 Heroku 上,应用程序是完全独立的,不依赖于将网络服务器运行时注入到执行环境中来创建面向网络的服务。每个 Web 进程只绑定到一个端口,并侦听来自该端口的请求。要绑定的端口由 Heroku 分配为 PORT 环境变量。
与 Heroku 的契约是让进程绑定到一个端口来服务请求。Heroku 的路由器负责将 HTTP 请求定向到正确端口上的进程。
Reference: Heroku Runtime Principles - Web Servers
回答by mkupiniak
You can do for example:
你可以做例如:
const PORT = process.env.PORT || 5001;
app.listen(PORT, () => console.log(`Server is listening on port ${PORT}...`));
回答by wscourge
In my case, heroku was listening on the default HTTPS port: 443and it was not visible via heroku config:get PORT.
就我而言,heroku 正在侦听默认的 HTTPS 端口:443并且通过heroku config:get PORT.

