Tutorial

How To Use PM2 to Setup a Node.js Production Environment On An Ubuntu VPS

Published on January 10, 2014
author

Jim Cassidy

How To Use PM2 to Setup a Node.js Production Environment On An Ubuntu VPS
Not using Ubuntu 12.04?Choose a different version or distribution.
Ubuntu 12.04

Introduction


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.

Create a Safe Account to Run Your Code


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:

  • Create the user with a folder in /home/safeuser/:
useradd -s /bin/bash -m -d /home/safeuser -c "safe user" safeuser
  • Create a password for safeuser - you will be asked to type it twice after you enter the following command:
passwd safeuser
  • Give the safe user permission to use root level commands:
usermod -aG sudo username

Login as the Safe User


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

Install GIT


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.

Install Latest Node.JS


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.

Give Safe User Permission To Use Port 80


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.

Use NPM To Install A Package Called PM2.


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:

  1. 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.)

  2. 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

Create a Simple Node App


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.

Run your app using PM2, and ensure that your node.js application starts automatically when your server restarts


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:

Img

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.

Learn more about our products

About the author(s)

Category:
Tutorial

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
30 Comments
Leave a comment...

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!

What does the “usermod -aG sudo &ltusername>” command do as I’m getting a error: bash: syntax error near unexpected token `newline’

Thanks

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
January 12, 2014

@sharry: There’s a typo – I’ve updated it. Try now.

@sharry. This command will add the user to the group of users who are allowed to use sudo to run root commands. The ‘a’ is important because it appends the group to the list of groups your user belongs to - otherwise, your user would l lose membership in other groups.

@Jim thanks for explanation.

Very nice tutorial, thanks for this!

PS: The links to the Git book and pm2 repository both have a comma at the end of the url causing 404 errors

When I input the following

 sudo npm install pm2 -g

I get an error message

npm http GET https://registry.npmjs.org/configurable/0.0.1

npm http GET https://registry.npmjs.org/escape-regexp/0.0.1 npm http 304 https://registry.npmjs.org/bindings

usage@0.3.9 install /usr/local/lib/node_modules/pm2/node_modules/usage node-gyp rebuild

gyp WARN EACCES user “root” does not have permission to access the dev dir “/home/nodeuser/.node-gyp/0.10.24” gyp WARN EACCES attempting to reinstall using temporary dev dir “/home/nodeuser/tmp/.node-gyp”

How do I preceed from here?

When you see the “gyp permissions error”, try installing with --unsafe-perm. For a bit more discussions see: https://github.com/TooTallNate/node-gyp/issues/454

Hi - those look like warnings, not errors. You can see in the last line that the script attempts to reinstall using the temporary dev dir.

I installed pm2 on my droplet to see if I saw the same thing you did - I did. The good news it that the install succeeded despite the warnings.

One way to find out if the install went well even with warnings is to go to the command line and type pm2. If you see a help screen - you are good to go! I am pretty sure you will find that all is well.

Please find below the output from a successful instead - you will notice the same warnings. Good luck, my friend.

gyp WARN EACCES user “root” does not have permission to access the dev dir “/root/.node-gyp/0.10.24” gyp WARN EACCES attempting to reinstall using temporary dev dir “/usr/lib/node_modules/pm2/node_modules/usage/.node-gyp” gyp http GET http://nodejs.org/dist/v0.10.24/node-v0.10.24.tar.gz gyp http 200 http://nodejs.org/dist/v0.10.24/node-v0.10.24.tar.gz make: Entering directory /usr/lib/node_modules/pm2/node_modules/usage/build' CXX(target) Release/obj.target/sysinfo/src/binding.o SOLINK_MODULE(target) Release/obj.target/sysinfo.node SOLINK_MODULE(target) Release/obj.target/sysinfo.node: Finished COPY Release/sysinfo.node make: Leaving directory /usr/lib/node_modules/pm2/node_modules/usage/build’ npm http GET https://registry.npmjs.org/keypress npm http 200 https://registry.npmjs.org/keypress /usr/bin/pm2 -> /usr/lib/node_modules/pm2/bin/pm2 pm2@0.7.1 /usr/lib/node_modules/pm2 ├── debug@0.7.4 ├── commander@2.1.0 ├── eventemitter2@0.4.13 ├── pm2-interface@0.1.0 ├── watch@0.8.0 ├── colors@0.6.2 ├── cron@1.0.1 ├── async@0.2.9 ├── cli-table@0.2.0 (colors@0.3.0) ├── axon@1.0.0 (escape-regexp@0.0.1, configurable@0.0.1) ├── pm2-multimeter@0.1.2 (charm@0.1.2) ├── coffee-script@1.6.3 ├── axon-rpc@0.0.2 (commander@1.0.5) └── usage@0.3.9 (bindings@1.1.1)

Sorry - I investigated further to see what the problem might be with sudo npm install pm2 -g. I often double check - I started from a fresh Droplet. I did find a problem.

The key is to remove /home/nodeuser/tmp and recreate it. Then try sudo npm install pm2 -g again. That worked for me. Don’t know why this happens. Good luck.

removing /home/noduser/tmp and recreating it worked a charm! :) Thanks a million!

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

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

*** UPDATED

  • Sorry i did not see the Question above… But i have the same issue.
Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
February 14, 2014

Check out <a href=“https://github.com/Unitech/pm2#a8”>https://github.com/Unitech/pm2#a8</a>, pm2 was recently updated to support more OSes.

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 David. Try typing ‘whereis node’ at the commandline. This will tell you where node is installed. Try that path. Good luck.

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!

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
February 22, 2014

@David: Glad I was able to help! BTW—I didn’t write the article, Jim did :]

When I install the PM2 I have got the following errors please help:

usage@0.3.9 install /root/local/lib/node_modules/pm2/node_modules/usage node-gyp rebuild

sh: 1: node-gyp: Permission denied npm http 304 https://registry.npmjs.org/escape-regexp/0.0.1 npm http 304 https://registry.npmjs.org/mkdirp npm ERR! usage@0.3.9 install: node-gyp rebuild npm ERR! Exit status 127 npm ERR! npm ERR! Failed at the usage@0.3.9 install script. npm ERR! This is most likely a problem with the usage package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! node-gyp rebuild npm ERR! You can get their info via: npm ERR! npm owner ls usage npm ERR! There is likely additional logging output above.

npm ERR! System Linux 3.11.0-12-generic npm ERR! command “/root/local/bin/node” “/root/local/bin/npm” “install” “pm2” “-g” npm ERR! cwd /root npm ERR! node -v v0.10.26 npm ERR! npm -v 1.4.3 npm ERR! code ELIFECYCLE npm http 200 https://registry.npmjs.org/colors/-/colors-0.3.0.tgz npm http 304 https://registry.npmjs.org/keypress npm ERR! npm ERR! Additional logging details can be found in: npm ERR! /root/npm-debug.log npm ERR! not ok code 0

Installing using node v0.11.12 causes an error when running pm2 commands. The error is as follows:

onizer: …/deps/uv/src/unix/core.c:431: uv__close: Assertion `fd > -1’ failed.

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
March 25, 2014

@waygee: Try installing 0.11.11 or 0.11.13, does that work?

Thanks for the tutorial. I’m using the MEAN stack image and a couple steps didn’t work for me.

Instead of sudo setcap cap_net_bind_service=+ep /usr/local/bin/node

I had to do sudo setcap cap_net_bind_service=+ep /usr/bin/nodejs

Also instead of sudo env PATH=$PATH:/usr/local/bin pm2 startup -u safeuser

I had to do sudo env PATH=$PATH:/usr/bin pm2 startup ubuntu -u safeuser

Setting up the startup also didn’t work for me the first time but after I rebooted my droplet and manually restarted my node server subsequent reboots automatically restarted my node server.

When I run sudo make install and try to check if node is installed afterwards with node -v, I dont get any feedback form the terminal about it being installed or not. Does anyone have any suggestions?

Great article, Jim. Just to note that, certainly in the current Ubuntu LTS 14.04, you can skip the whole build thing and just run

sudo apt-get install nodejs npm

with the bonus that it’s always up to date.

This will probably solve @aristides problem too :)

Hi, I got this message when run pm2 my app.

Express app started on port 80 Error: bind EACCES

Please help me to solve this. Thanks

Regards

@Jonathan

I believe the reason why building Node.JS (and NPM) from source may be preferred is to guarantee an up-to-date version. The package system used by Ubuntu (and other package systems) rely on the package system maintainers updating the packages when they discover there is a new version ready and create a package designed to work on all deployments of that OS; this can be quite delayed from the actual release schedule of a project.

@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.

Be careful: installing pm2 globally as root will give any user of the system the ability to run anything through pm2 start X as root.

See this github issue for more information #329

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
July 15, 2014

@double.ypsilon: That only applies if you’re starting pm2 as root. In this article, pm2 is started as “safeuser” and not root.

You are right johnbrett7 - I have subsequently mended my ways. Mea culpa.

Thanks for the kind words.

Port 80 still shows as in use

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.