Question

Node.js throws following error while running on http port 80 (default port):-

Error: EACCES, Permission denied
    at Server._doListen (net.js:1062:5)
    at net.js:1033:14
    at Object.lookup (dns.js:132:45)
    at Server.listen (net.js:1027:20)
    at [object Context]:1:3
    at Interface.<anonymous> (repl.js:150:22)
    at Interface.emit (events.js:42:17)
    at Interface._onLine (readline.js:132:10)
    at Interface._line (readline.js:387:8)
    at Interface._ttyWrite (readline.js:564:14)

I figured out that node needs to have root access.

Conventionally we avoid giving root access in normal situation. What's the best practices for using it on port 80 (or port<1024).

This link has the same question but it has only one answer i.e. PREROUTING. While my solution provides other ways as well.

I am writing this to have all answers at one location, as I have to go thorough other resources than PREROUTING. Why not all answers at one location for sharing the knowledge

Was it helpful?

Solution

FYI: You cannot run socket on ports < 1024 with normal user permission. You need to have root access for it.

There are total 3 ways to solve the error:-


1. Give root access and run it (which is usual one)

2. Redirect to other port

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

Then launch my Node.js on port 3000. Requests to port 80 will get mapped to port 3000.

You should also edit your /etc/rc.local file and add that line minus the sudo. That will add the redirect when the machine boots up. You don't need sudo in /etc/rc.local because the commands there are run as root when the system boots.

Reference Link

3. Give Normal user capability of using sockets as root

Objective:- We are not providing full root access and only giving socket_root permission to access it by normal user to run your server on any port.

we do NOT want to run your applications as the root user, but there is a hitch: your safe user does not have permission to use the default HTTP port (80). You goal is to be able to publish a website that visitors can use by navigating to an easy to use URL like http://localhost.

Unfortunately, unless you sign on as root, you’ll normally have to use a URL like http://localhost:3000 - notice the port number.

A lot of people get stuck here, but the solution is easy. There a few options but this is the one I like. Type the following commands:

sudo apt-get install libcap2-bin
sudo setcap cap_net_bind_service=+ep `readlink -f \`which node\``

Now, when you tell a Node application that you want it to run on port 80, it will not complain.

Reference Link

General Info Reference link from apache

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top