Skip to content

Instantly share code, notes, and snippets.

@WesThorburn
Last active March 11, 2024 07:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WesThorburn/7b06a60e53bd1d80496c5de8f01947e9 to your computer and use it in GitHub Desktop.
Save WesThorburn/7b06a60e53bd1d80496c5de8f01947e9 to your computer and use it in GitHub Desktop.
Configuring PM2 to daemonize a task

Configuring PM2 to daemonize a task

  • Install pm2: sudo npm install pm2 -g
  • Start the process: sudo pm2 start path/to/process.js
  • Optionally pass command line flags like so: sudo pm2 start path/to/process.js -- --port 8080
  • Optionally provide an alias like so: sudo pm2 start npm --name "your-app-alias" -- start
  • Initialize the launch configuration: sudo pm2 startup
  • Save the configuration: sudo pm2 save
  • Optionally test that it works by restarting the server: sudo shutdown -r now

Without sudo

Some applications, Puppeteer for example cannot run with admin privileges. Follow these steps to daemonize the task without running the task with sudo.

  • Run as the non root user: pm2 startup -u <YOUR NON ROOT USER>
  • A command will be printed to the console, copy it and run it: env PATH=$PATH:/usr/bin pm2 startup systemd -u <YOUR NON ROOT USER> --hp /home/<YOUR NON ROOT USER>
  • Switch to the root user and run (same as above): env PATH=$PATH:/usr/bin pm2 startup systemd -u <YOUR NON ROOT USER> --hp /home/<YOUR NON ROOT USER>
  • Switch back to the non root user and run: pm2 start <YOUR /PATH/TO/INDEX.JS> --name <YOU_APPLICATION_NAME>
  • Still as the non root user, run: pm2 save
  • And then try rebooting: sudo shutdown -r now

Uninstalling pm2

  • Kill the process: sudo pm2 kill
  • Uninstall pm2: sudo npm remove pm2 -g
  • After removal which pm2 won't return a version

Delete the /home/user/.pm2 directories by running: sudo rm -rf /home/user/.pm2 It's also possible that there will be an extra pm2 configuration file located in /etc/init.d/ that'll need to be removed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment