express – What is process.env.PORT in Node.js?
express – What is process.env.PORT in Node.js?
In many environments (e.g. Heroku), and as a convention, you can set the environment variable PORT
to tell your web server what port to listen on.
So process.env.PORT || 3000
means: whatever is in the environment variable PORT, or 3000 if theres nothing there.
So you pass that to app.listen
, or to app.set(port, ...)
, and that makes your server able to accept a what port to listen on parameter from the environment.
If you pass 3000
hard-coded to app.listen()
, youre always listening on port 3000, which might be just for you, or not, depending on your requirements and the requirements of the environment in which youre running your server.
-
if you run
node index.js
,Node will use3000
-
If you run
PORT=4444 node index.js
, Node will useprocess.env.PORT
which equals to4444
in this example. Run withsudo
for ports below 1024.
express – What is process.env.PORT in Node.js?
When hosting your application on another service (like Heroku, Nodejitsu, and AWS), your host may independently configure the process.env.PORT
variable for you; after all, your script runs in their environment.
Amazons Elastic Beanstalk does this. If you try to set a static port value like 3000
instead of process.env.PORT || 3000
where 3000 is your static setting, then your application will result in a 500 gateway error because Amazon is configuring the port for you.
This is a minimal Express application that will deploy on Amazons Elastic Beanstalk:
var express = require(express);
var app = express();
app.get(/, function (req, res) {
res.send(Hello World!);
});
// use port 3000 unless there exists a preconfigured port
var port = process.env.PORT || 3000;
app.listen(port);