'AWS EC2 AMI User Data run PM2

I want to start my application on an instance boot. I used the following user data, but I'm unable to see any process running in pm2.

Note: Creating an instance using an AMI. NodeJs, PM2 and all the dependencies areinstalled. I can SSH to server and start my application using pm2 manually.

#!/bin/bash
pm2 start /home/ubuntu/foyrinfrasubscription/server/server.js --name "ReportSub"
pm2 save
pm2 resurrect


Solution 1:[1]

I recommend using pm2 startup command to create init services script

Manual:

https://pm2.keymetrics.io/docs/usage/startup/

Example:

https://futurestud.io/tutorials/pm2-restart-processes-after-system-reboot

Solution 2:[2]

I had some issues with this because I wanted to set environment variables using user data and the regular pm2 startup script by default also runs at the same time as the user data (cloud-final) script is run.

I found a really hacky way to do this - I wouldn't advise it:

First I had to change the order that pm2 starts up to make sure it fires AFTER the user data settings reference: https://serverfault.com/questions/871328/start-service-after-aws-user-data-has-run

Then, I couldn't find a way to set environment variables because they were in a different session. Dumping to .bashrc and /etc/profiles didn't work. So, I just modified .pm2/dump.pm2 with my settings.

If anyone has any advice about how to do this better, that would be great!

Solution 3:[3]

In addition to setting up pm2 via systemd as described in the other answers, using a pm2 "ecosystem" file allows passing environment variables harvested in User Data. As the setup would likely be oriented to running a specific node service vs. a generic pm2-managed server, the systemd service file can be updated to use the ecosystem file programmatically edited in User Data flow, e.g.,

ExecStart=/usr/lib/node_modules/pm2/bin/pm2 start /etc/systemd/system/pm2-ecosystem-my.config.js

and the ExecReload line commented out (optionally)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AWS PS
Solution 2 Photis
Solution 3 SVUser