I would like to run node with a low privileges user, is it possible? I need to use the framework Express.js
-
2Define "low privileges user." – Matt Ball Nov 29 '11 at 14:14
-
I don't want to tun node.js with ROOT privileges. – Dail Nov 29 '11 at 14:25
-
What makes you think you have to? I've never needed to do so. – Matt Ball Nov 29 '11 at 14:27
-
1You only need root access to run node on port 80. – Pono Nov 29 '11 at 15:19
-
4@pono: all port under 1024 need root access – malletjo Nov 29 '11 at 18:43
1 Answers
Yes. There are many solutions available to do this, depending on your exact needs.
If you want to run node on port 80, you can use nginx (doesn't work with WebSockets yet) or haproxy. But perhaps the quickest and dirtiest is to use iptables to redirect port 80 to the port of your choice:
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8003
sudo iptables -t nat -L
When you’re happy, then save the config and make sure iptables comes on at boot
sudo service iptables save
sudo chkconfig iptables on
To automatically start your nodejs service as non-root, and restart it if it fails, you can utilize upstart with a script like this:
#!upstart
description "nodeapp"
author "you"
start on started mountall
stop on shutdown
# Automatically Respawn:
respawn
respawn limit 99 5
script
export HOME="/home/user/"
exec sudo -u user /usr/local/bin/node /home/user/app.js 2>&1 >> /home/user/app.log
end script
If you're on an Amazon EC2 installation, or you get an error that says sudo: sorry, you must have a tty to run sudo
, then you can replace your exec command with this:
#!upstart
description "nodeapp"
author "you"
start on started mountall
stop on shutdown
# Automatically Respawn:
respawn
respawn limit 99 5
script
export HOME="/home/user/"
#amazon EC2 doesn’t allow sudo from script! so use su --session-command
exec su --session-command="/usr/local/bin/node /home/user/app.js 2>&1 >> /home/user/app.log" user &
end script
And, you didn't ask this question, but to keep it running forever, check out monit! Here is a useful guide to setting up node.js with upstart and monit.

- 40,352
- 6
- 119
- 149
-
-
1Depending on the specific version of node you are using, what your directory structure looks like, and whether node was installed by root or the current user, the answer varies between everything and nothing :) It may tell node where it's going to be run from, it may be completely ignored (note that I incorrectly put `/home/user/nodeapp` in my example, when it should match the app.js location of `/home/user/`, i.e. where require() is going to look for modules) – Kato Feb 06 '12 at 15:50
-
On EC2 my Ubuntu (12.04) didn't have a `--session-command` switch for `su`. I ran `exec su - $USER -c '/usr/bin/node /path/to/node/app.js 2>&1 >> /path/to/node/app.log'` – Dmitry Minkovsky Nov 25 '12 at 06:15
-
That's another option and a great choice; I'm surprised you'd need even that for Ubuntu – Kato Nov 25 '12 at 18:53