简体   繁体   中英

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

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

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!

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, eg,

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

and the ExecReload line commented out (optionally)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM