What is process.env.PORT in Node.js?
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.
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.
Amazon's 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 Amazon's 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);
In some scenarios, port
can only be designated by the environment and is saved in a user environment variable. Below is how node.js apps work with it.
The process
object is a global that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using require()
.
The process.env
property returns an object containing the user environment.
An example of this object looks like:
{
TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node'
}
For example,
terminal: set a new user environment variable, not permanently
export MY_TEST_PORT=9999
app.js: read the new environment variable from node app
console.log(process.env.MY_TEST_PORT)
terminal: run the node app and get the value
$ node app.js
9999
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 there's 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()
, you're 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 you're running your server.