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

后端 未结 3 1410
天命终不由人
天命终不由人 2021-02-02 14:15

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

相关标签:
3条回答
  • 2021-02-02 14:47

    (I haven't got enough reputation to add a comment the the one of Matt Browne, so I write this as an answer. Feel free to edit.)

    There is a simpler method to load iptables rules automatically after a reboot than the one described in the link of Matt Browne: One can install iptables-persistent from the repositories using apt-get:

    apt-get install iptables-persistent
    

    Rules still need to be saved manually like this:

    IPv4:

    iptables-save > /etc/iptables/rules.v4
    

    IPv6:

    iptables-save > /etc/iptables/rules.v6
    

    (Source: http://www.thomas-krenn.com/de/wiki/Iptables_Firewall_Regeln_dauerhaft_speichern (german))

    0 讨论(0)
  • 2021-02-02 14:57

    I love the simplicity of this workaround:

    sudo setcap 'cap_net_bind_service=+ep' `which node`
    

    It also works for programs other than nodejs btw.

    Basically as 2nd parameter you type the path to the program executable (like /usr/bin/nodejs on Ubuntu), in the above case which node should provide it dynamically, thus making this work independently from Linux distro.

    Beware though that when you upgrade nodejs or the executable gets overwritten for some other reason you would have to execute that same command again.

    Sources:

    • How to: Allow Node to bind to port 80 without sudo,
    • Is there a way for non-root processes to bind to "privileged" ports on Linux?
    0 讨论(0)
  • 2021-02-02 15:12

    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.

    0 讨论(0)
提交回复
热议问题