if you run node index.js
,Node will use 3000
If you run PORT=4444 node index.js
, Node will use process.env.PORT
which equals to 4444
in this example. Run with sudo
for ports below 1024.
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
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);
Source: Stackoverflow.com