Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express app server . listen all interfaces instead of localhost only

I'm very new for this stuff, and trying to make some express app

var express = require('express');
var app = express();

app.listen(3000, function(err) {
    if(err){
       console.log(err);
       } else {
       console.log("listen:3000");
    }
});

//something useful
app.get('*', function(req, res) {
  res.status(200).send('ok')
});

When I start the server with the command:

node server.js 

everything goes fine.

I see on the console

listen:3000

and when I try

curl http://localhost:3000

I see 'ok'.

When I try

telnet localhost

I see

Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]' 

but when I try

netstat -na | grep :3000

I see

tcp  0  0 0.0.0.0:3000   0.0.0.0:*  LISTEN

The question is: why does it listen all interfaces instead of only localhost?

The OS is linux mint 17 without any whistles.

like image 920
Pavel L Avatar asked Nov 27 '15 08:11

Pavel L


3 Answers

If you don't specify host while calling app.listen, server will run on all interfaces available i.e on 0.0.0.0

You can bind the IP address using the following code

app.listen(3000, '127.0.0.1');

If you want to run server in all interface use the following code

app.listen(3000, '0.0.0.0');

or

app.listen(3000)
like image 69
Vishnu Avatar answered Oct 11 '22 13:10

Vishnu


From the documentation: app.listen(port, [hostname], [backlog], [callback])

Binds and listens for connections on the specified host and port. This method is identical to Node’s http.Server.listen().

var express = require('express');
var app = express();
app.listen(3000, '0.0.0.0');
like image 21
Julien Le Coupanec Avatar answered Oct 11 '22 14:10

Julien Le Coupanec


document: app.listen([port[, host[, backlog]]][, callback])

example:

const express = require('express');
const app = express();
app.listen('9000','0.0.0.0',()=>{
      console.log("server is listening on 9000 port");
})

Note: 0.0.0.0 to be given as host in order to access from outside interface

like image 14
Thavaprakash Swaminathan Avatar answered Oct 11 '22 13:10

Thavaprakash Swaminathan