Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run Node.js on port 80?

My aim is to run Node.js on port 80. This is because I am finding node.js is being blocked from certain networks which do not allow traffic from any other port.

It appears that the best way to do this is by proxying Apache through Node.js. I have tried using node-http-proxy to do this but I have not had any luck.

The code I am using is here:

var util = require('util'),     http = require('http'),     httpProxy = require('http-proxy');  httpProxy.createServer(9000, 'localhost').listen(80);  http.createServer(function (req, res) {   res.writeHead(200, { 'Content-Type': 'text/plain' });   res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));   res.end(); }).listen(9000); 

But I keep getting the error "Address in use" for port 80. I must be doing something wrong.

How do I proxy Apache through node.js using node-http-proxy? Will this enable me to run node.js on port 80? And is node-http-proxy the best way to achieve this?

Thank you.

like image 969
Kit Avatar asked May 24 '11 10:05

Kit


People also ask

Can I run NodeJS on port 80?

If you want to run NodeJS on different port, change 80 to your required port number (e.g 8080). Also the function defined in createServer() will be executed whenever someone sends a request to your NodeJS server.

How do I run node js without a port?

When users give browsers URLs without ports, they automatically apply the default port. For URLs like http://example.com/ or http://10.11.12.13/ the default port is 80. For https://example.com it's 443, and you need to use the https server class. So, you can make your server listen on port 80.

What is the default port for NodeJS?

The 3000 port is used because in the Nodejs application code the port mentioned to run the node application is 3000 in most of the sample code provided on internet.


2 Answers

run your app on a high port 8080 or whatev then

sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080 

If you are not using ngnix or apache

like image 86
fullstacklife Avatar answered Oct 09 '22 09:10

fullstacklife


The simplest solution: safely configure your node app to run on port 80.

  • sudo apt-get install libcap2-bin
  • sudo setcap cap_net_bind_service=+ep /path/to/node
  • Ta da! You're done.

Why do I like it?

  • You don't have to use apache or nginx
  • You don't have to run your application as root
  • You won't have to forward ports (and handle that each time your machine boots)

Reference Link: https://www.digitalocean.com/community/tutorials/how-to-use-pm2-to-setup-a-node-js-production-environment-on-an-ubuntu-vps (A great article on how to set up your node app on cloud hosting).

like image 41
Kyle Chadha Avatar answered Oct 09 '22 08:10

Kyle Chadha