This tutorial aims to help you setup up an Ubuntu server to run Node.js applications, including apps based on Express, Geddy, or Sails. These instructions will help you avoid some security mistakes, as well as provide some surprising benefits such as:
You will not run your app as root; therefore, your app will be more secure.
You will be using port 80 to run your app, which typically can only be accessed by the root user. (You will able to run your app using a custom URL such as http://mysite.com - but you will not have to specify a port.)
Your application will restart if it crashes, and it will keep a log of unhandled exceptions.
Your application will restart when the server starts - i.e. it will run as a service.
These instructions assume that the reader has only a basic knowledge of Linux. You may skip the information that you do not need, but following the steps closely may provide some advantages.
When you first set up your DigitalOcean droplet, you received instructions to log on using the root account. The instructions looked something like this:
To login to your droplet, you will need to open a terminal window and copy and paste the following string:
ssh root@192.241.xxx.xxx
Please note, ‘192.241.xxx.xxx’ will be different for you. Simply follow the instructions you received from DigitalOcean when your virtual server was setup and log on using ssh.
As most of us understand, if you run your code using the root account, and if a hostile party compromises the code, that party could get total control of your VPS.
To avoid this, let’s setup a safe account that can still perform root operations if we supply the appropriate password. For the purposes of this tutorial, let’s call our safe user “safeuser”– you can name it whatever you like. For now, log on as the root user and follow these steps:
/home/safeuser/
:useradd -s /bin/bash -m -d /home/safeuser -c "safe user" safeuser
safeuser
- you will be asked to type it twice after you enter the following command:passwd safeuser
usermod -aG sudo username
Log out of your DigitalOcean root session by pressing ctrl-D.
Please note that the command to log on as the safe user is the same command you used before, but the user name has changed. Once you have logged on as the safe user, every time you want to run a command that has root privileges, you are going to have to proceed the command with the word sudo. From the command line on your own machine, log on using the command that appears below.
ssh safeuser@192.241.xxx.xxx
One you have logged on, install GIT (we are going to use GIT to install Node.js.). If, for any reason, you are unfamiliar with GIT, it is a beautiful tool that is going to become a big part of your life. Read the GIT book if you want to know more. Installing it on Ubuntu is easy:
sudo apt-get install git
The word sudo indicates that you want to run this command as root. You will be prompted for your password - i.e. the safe user password. When you provide your password, the command will run.
Please note that v0.10.24 is the most recent version of Node as of this writing. If there is a newer version, please use that version number instead.
Type the following commands, one line at a time, and watch the magic as your droplet downloads, compiles, and installs the Node.js:
sudo apt-get install build-essential
sudo apt-get install curl openssl libssl-dev
git clone https://github.com/joyent/node.git
cd node
git checkout v0.10.24
./configure
make
sudo make install
When you type sudo make, a lot of things are going to happen. Be patient.
When the make install process ends, make sure all went well by typing:
node -v
If all went well, you should see: v0.10.24.
Remember, we do NOT want to run your applications as the root user, but there is a hitch: your safe user does not have permission to use the default HTTP port (80). You goal is to be able to publish a website that visitors can use by navigating to an easy to use URL like http://mysite.com.
Unfortunately, unless you sign on as root, you’ll normally have to use a URL like http://mysite.com:3000 - notice the port number.
A lot of people get stuck here, but the solution is easy. There a few options but this is the one I like. Type the following commands:
sudo apt-get install libcap2-bin
sudo setcap cap_net_bind_service=+ep /usr/local/bin/node
Now, when you tell a Node application that you want it to run on port 80, it will not complain.
NPM is a package manager that you will use to install frameworks and libraries to use with your Node.js applications. NPM was installed with Node.js. PM2 is a sweet little tool that is going to solve two problems for you:
It is going to keep your site up by restarting the application if it crashes. These crashes should NOT happen, but it is good know that PM2 has your back. (Some people may be aware of Forever.js, another tool that is used to keep node based sites running - I think you will find that PM2 has a lot to offer.)
It is going to help you by restarting your node application as a service every time you restart the server. Some of use know of other ways to do this, but pm2 makes it easier, and it has some added flexibility.
Install PM2 by typing thr following at the command line:
sudo npm install pm2 -g
This is where you can test your environment to be sure everything is working as it should. In this example, I will use the IP address, but your goal should be to use a domain name. Look at these instructions later: How To Set Up a Host Name with DigitalOcean
First, create a simple node app just for testing. At the command line type:
nano app.js
Then enter the following lines of code into the nano editor:
var http = require('http');
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
});
server.listen(80);
console.log("Server running at http://127.0.0.1:80/");
Press ctrl-X to exit - when nano asks if you want to save, answer yes.
Now you have a node based application called app.js that you can use to test your environment.
You can run app.js at the command line by typing: node app.js
Do that, and you should be able to see your hello world text by using a browser and typing your IP address as the URL. You can interrupt execution by pressing crtl-C. This is NOT how we want to run our application. There is a MUCH better way. We will use PM2 to run it instead of using Node directly.
There are some huge benefits for you if you run your application using pm2. Instead of running your app as above, run it using the following command:
pm2 start app.js
You should see this report:
What are the advantages of running your application this way?
PM2 will automatically restart your application if it crashes.
PM2 will keep a log of your unhandled exceptions - in this case, in a file at /home/safeuser/.pm2/logs/app-err.log.
With one command, PM2 can ensure that any applications it manages restart when the server reboots. Basically, your node application will start as a service.
Run this command to run your application as a service by typing the following:
sudo env PATH=$PATH:/usr/local/bin pm2 startup -u safeuser
Please note, you may not be using safeuser as the user name - use the name that corresponds to your setup. You should see the following report:
Adding system startup for /etc/init.d/pm2-init.sh ...
/etc/rc0.d/K20pm2-init.sh -> ../init.d/pm2-init.sh
/etc/rc1.d/K20pm2-init.sh -> ../init.d/pm2-init.sh
/etc/rc6.d/K20pm2-init.sh -> ../init.d/pm2-init.sh
/etc/rc2.d/S20pm2-init.sh -> ../init.d/pm2-init.sh
/etc/rc3.d/S20pm2-init.sh -> ../init.d/pm2-init.sh
/etc/rc4.d/S20pm2-init.sh -> ../init.d/pm2-init.sh
/etc/rc5.d/S20pm2-init.sh -> ../init.d/pm2-init.sh
Now our stated objectives have been reached!
You are not running as root; therefore, your app is more secure.
You are using port 80, which can usually only be used by the root user.
Your application will restart if it crashes, and it will keep a log on unhandled exceptions.
Your application will restart when the server starts.
Have fun! This is a fairly robust setup to start with.
**After thought: ** You may notice a file folder called node in the safeuser directory. It was used during installation, but you no longer need it. You can delete it by typing the following:
rm -rf /home/safuser/node
There is a lot more to learn about node, but this tutorial will put you on the right path. To learn more about pm2, visit the pm2 repo
Important Clarification: There is a startup script that starts your Node applications, but you will avoid a lot of confusion if you understand how it works. The script is called ‘pm2-init.sh.’ It lives in the ‘etc/init.d/’ directory, but it does NOT start app.js. Instead, it starts the programs that were running under PM2 the last time the server shutdown.
This is important. If your node application does not show up in the list when you type pm2 list, then your app will not restart when the server restarts. Follow the proper instructions for starting your apps using pm2 to ensure that they will restart: pm2 start app.js
By Jim Cassidy
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Hi All –
Thanks Jim, I’ll look into it.
For everyone having an issue with this: sudo env PATH=$PATH:/usr/local/bin pm2 startup -u safeuser
you need to add your linux platform Distro name that they support - Look below for my sample
sudo env PATH=$PATH:/usr/local/bin pm2 startup ubuntu -u safeuser
Just substitute your Linux Distro for what they support
ubuntu works for Debian7.x Wheezy and created the scripts without error.
A little work and its running the clustered services and managing them without issue. I did build a custom .json file to allow me to pass args to my script. And pm2 has a demo script to show you.
$ pm2 generate <CHOOSE-NAME>.json
Here is my sample: name.json
[{ “name” : "NODE SAMPLE json ", “script” : “SCRIPTNAME.js”, “args” : “[‘–production’ ,‘–loglevel’, ‘{0,1,2}’,‘–standalone’, ‘webserver’]” }]
from the command line I run:
$ pm2 start -i 3 NAME.json
This enables me to use the 8 cpu’s on my machine - 3 for the node app, 3 for another and 2 for admin access and system reporting.
Again thanks to Jim and everyone else for the comments which sparked a day of learning.
Thanks for the tutorial Kamal!
Thanks for the article! I also had to run
pm2 save
after starting my app to get pm2 to remember what it should run after the server is rebooted. http://pm2.keymetrics.io/docs/usage/startup/May you mention the
pm2 save
command? Just starting apps might not suffice.It’ll dump the process list, on startup pm2 will call
pm2 resurrect
, which will reload the previous dumped files.Thanks!
@Jim Great article, the port 80 trick is very handy!
One point on security though, sudo should never be used to install global packages as emphasised by the NPM maintainer Issac Schlueter (http://howtonode.org/introduction-to-npm):
“I strongly encourage you not to do package management with sudo! Packages can run arbitrary scripts, which makes sudoing a package manager command as safe as a chainsaw haircut. Sure, it’s fast and definitely going to cut through any obstacles, but you might actually want that obstacle to stay there.”
safeuser shouldn’t have sudo access at all in this tutorial. Node, git and port 80 should all be provisioned by root, then safeuser could simply configure global npm installs to their home directory using this script I wrote: https://github.com/johnbrett/safe-npm-global meaning they would never need sudo access, making everything much more secure.
Since Ubuntu and Debian share so much, I’m setup testing this on Debian 7, 64 bit and am having persistent errors:
sudo setcap cap_net_bind_service=+ep /usr/local/bin/node
Failed to set capabilities on file `/usr/local/bin/node’ (No such file or directory)
Just to see, next I created a directory called node and ran it again getting a slightly different error:
sudo setcap cap_net_bind_service=+ep /usr/local/bin/node Failed to set capabilities on file `/usr/local/bin/node’ (Invalid argument) The value of the capability argument is not permitted for a file. Or the file is not a regular (non-symlink) file
Hi After this sudo env PATH=$PATH:/usr/local/bin pm2 startup -u safeuser i have error: error: missing required argument `platform’
What would that be?
Thanks
Hi On running the command sudo env PATH=$PATH:/usr/local/bin pm2 startup
I am requested to supply a ‘platform’ argument
(error: missing required argument `platform’)
What would that be? Thanks
I found pm2 is running the node app multiple times I used htop here is few lines. Using Ubuntu I added memory 3 times but now it going out of budget.
PM2 V5.2.0: GOD Deamon {/root/.pm2} X 10 Times npm run start X 12 Times node ./dist/server.js X 12 times
Hi there,
I have this working but for some reason PM2 creates multiple (3) processes. Is this a problem and why is this happening?
Great article, thanks!
For anyone struggling with the setcap line, this seemed to work for me (ubuntu 14.04 + nodejs)
sudo setcap cap_net_bind_service=+ep
readlink -f \
which node``Hope that will help you guys.