How to run node.js as non-root user?

user2208171 picture user2208171 · Jul 4, 2013 · Viewed 11.1k times · Source

I'm running a node.js server, that will serve requests on port 80 amongst others. Clearly this requires the application running as root (on Linux).

Looking at this post (http://syskall.com/dont-run-node-dot-js-as-root) as an example it's clear that there are simple ways to allow node to be run as a non-root user, but I'm wondering if anyone has views on the advantages/disadvantages of the different methods suggested:

  1. code: use setuid() to drop down from root to non-priviledged user after listening on port 80 is established.

  2. using a proxy server of some sort to redirect requests to a port >1024 (and so not need node to run as root)

  3. using IP tables to forward to another port (ditto node would not run as root)

Thanks

Answer

Daniel picture Daniel · Jul 4, 2013

Option 1 requires you launch the node server as root. Not ideal.

Option 2 adds overhead to every handled request and adds another failure point to your stack.

Option 3 Is the simplest and most efficient method.

To implement Option 3, add the following to your system init scripts. (/etc/rc.d/rc.local on RedHat based systems like AWS).

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

That will redirect requests from port 80 to port 3000.