Run NodeJS with non-root / user permission using Runit in Ubuntu 12.04 Precise


After leaving NodeJS about 6 month, I still hard to find articles who explain how to running NodeJS services in production mode. This is mean, running NodeJS services by user permission (not by root) and can automatically restart if crashed. Well, this is not only for NodeJS cases, but you can also implement this solution for running Twisted services.

I use Ubuntu 12.04 Precise Pangolin at this guide. Don’t worry, it’s doesn’t have a big difference step with previous Ubuntu version. So, let start!

1. Install Runit

1
sudo apt-get install runit

2. Install NodeJS
I strongly suggest to install NodeJS without root permission. For guide, please have a look to my another tutorial in :

3. Configure runit

1
2
3
sudo chown ubuntu:ubuntu /etc/sv
cd /etc/sv && mkdir nodejs
cd nodejs && touch run

Now, we will edit “run” file by :

1
2
3
#!/bin/sh
exec 2>&1
exec chpst -U ubuntu:ubuntu runsvdir /home/ubuntu/service

So, what we doing is we will tell runit where the services that will be executed. At this example, i use “ubuntu” as my user. You can change it by your username.

Now, we try to create “service” folder in “/home/

1
2
3
cd ~/
mkdir service && mkdir nodejs
cd nodejs && touch run

Then, we will edit “run” file to running our NodeJS application :

1
2
#!/bin/sh
exec sudo -i -u ubuntu /home/ubuntu/local/node/bin/node /var/yodi/obrool.com/app.js

At this example, I will run “node /location/myapp/“. Remember to take fullpath of your node binary. For instance, “/home/ubuntu/local/node/bin/node” at this example. It’s depend on where your “node” binary installed.

Final steps, we just make symlinks from sv to services by :

1
2
3
sudo ln -s /etc/sv/nodejs /etc/service/
sudo chown -R ubuntu:ubuntu /etc/service/nodejs
sudo chown -R ubuntu:ubuntu /etc/sv/nodejs

Let’s run it by :

1
sv start nodejs

If you check using “ps aux | grep node”

1
2
3
4
5
root     17932  0.0  0.0    164     4 ?        Ss   13:16   0:00 runsv nodejs
root     17934  0.0  0.0    164     4 ?        S    13:16   0:00 runsv nodejs
root     17935  0.0  0.1  18996  1212 ?        S    13:16   0:00 sudo -i -u ubuntu /home/ubuntu/local/node/bin/node /var/yodi/obrool.com/app.js
ubuntu   17936  0.2  1.4 642256 15180 ?        Sl   13:16   0:02 /home/ubuntu/local/node/bin/node /var/yodi/obrool.com/app.js
ubuntu   18051  0.0  0.0   7964   876 pts/0    S+   13:35   0:00 grep –color=auto node

Yes, now NodeJS running by user “ubuntu” in pid 17936. It’s works!


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.