Unable to run NodeJS application on 80 port


Unable to run NodeJS application on port 80. Getting following exception

$ node index.js
events.js:182
      throw er; // Unhandled 'error' event
      ^
Error: listen EACCES 0.0.0.0:80
    at Object.exports._errnoException (util.js:1022:11)
    at exports._exceptionWithHostPort (util.js:1045:20)
    at Server.setupListenHandle [as _listen2] (net.js:1298:19)
    at listenInCluster (net.js:1363:12)
    at Server.listen (net.js:1463:7)
    at Function.listen (/home/experimental/helloWorld/node_modules/express/lib/application.js:618:24)
    at Object.<anonymous> (/home/experimental/helloWorld/index.js:6:5)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)

1 Answer

7 years ago by

Quick Solution (Not recommended):

Start your NodeJS application with sudo.

sudo node index.js

Right way to fix

To run anything under 1024 port you need sudo permission on Unix systems, so you need to start the service with root permissions.

But running the service sudo permissions is not really a good idea as it makes your system more vulnerable to attack. So following are some alternatives to run your service on 8080 and do port forwarding from 80 to 8080.

1. Using IP Tables

Execute the following commands to make iptables allow traffic on 80 and 8080

sudo iptables -I INPUT 1 -p tcp --dport 8080 -j ACCEPT
sudo iptables -I INPUT 1 -p tcp --dport 80 -j ACCEPT

Now execute the following command to forward port 80 traffic to 8080

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

2. Using Nginx

Add the following to nginx.conf

server {
        listen  80;
        location / {
            proxy_set_header    Host $host;
            proxy_set_header    X-Real-IP   $remote_addr;
            proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass  http://127.0.0.1:8080;
        }
}
7 years ago by Karthik Divi