Scripting PM2 startup for a non-root user

Posted on April 7, 2016

I’ve been working on a bash script for standing up a newly created Linux machine. This particular setup will be running node.js supported by the process manager pm2. In addition, I will be using the Node Version Manager (nvm), to pull down and install node.

My install script will not be run as root, but the pm2 startup command that respawns pm2 on boot needs root access. If you simply run the pm2 startup command as a non-root user, you’ll see this:

You have to run this command as root. Execute the following command:
sudo su -c "env PATH=$PATH:/home/userfoo/.nvm/versions/node/v5.9.1/bin pm2 startup linux -u userfoo --hp /home/userfoo"

I didn’t want to hard code the node version, the user name, or the home path, so I came up with the following bash script that will happily run for an arbitrary user and node version.