Running PM2 with a user systemctl service
I am running one node service on a linux host that should be started on system startup but since I don't have root on the machine, this requires a user systemctl service
To set up pm2 to start as systemctl a minor trickery is required to get the environment right so that pm2 finds its config files
First of all, create a service file in ~/.config/systemctl/user.control/pm2.service
[Unit] Description=pm2 [Service] Type=simple StandardOutput=journal ExecStart=/home/username/node_modules/pm2/bin/pm2 restart all EnvironmentFile=-/home/username/pm2_env.txt [Install] WantedBy=default.target
go to the node project dir and start it if you have not done so already
cd ~/project pm2 start pm2 save
Dump the environment to a file to make sure that the PATH environment is correct, this may or may not be required, the path is what pm2 startup systemd
suggests
env PATH=$PATH:/nix/store/7y1qagav6xv4k3w0df5d7z91y2d3w4z7-nodejs-18.13.0/bin >~/pm2_env.txt
not all environment settings are necessary, you can remove the ones that relate to programs that are not used during the startup process like ssh or X
start the service as systemctl service, this will restart the pm2 process and all defined processes
systemctl --user restart pm2.service
set the service to be started on boot
systemctl --user enable pm2.service
when the service is running it should display successful startup when running, as the pm2 program forks and exists, it is listed as dead/inactive, that is correct
systemctl --user status pm2.service
and
pm2 logs
should show logs