Skip to content

Instantly share code, notes, and snippets.

@steveneaston
Last active February 19, 2018 06:26
Show Gist options
  • Save steveneaston/58a33e6cc280ca07f4c5 to your computer and use it in GitHub Desktop.
Save steveneaston/58a33e6cc280ca07f4c5 to your computer and use it in GitHub Desktop.
Auto-start PM2 on Homestead or Vagrant

The Problem

PM2's startup service script is triggered before Vagrant mounts the local directories so none of the scripts it's tasked with starting can be found.

The solution

Use Upstart's events to trigger pm2 resurrect once local directories have been mounted.

Notice: At the time of writing, Vagrant's vagrant-mounted event is not being triggered on Ubuntu < 15.04. To fix this, you should add the following workaround:

Create a file called /etc/init/workaround-vagrant-bug-6074.conf with the following content:

# workaround for https://github.com/mitchellh/vagrant/issues/6074
start on filesystem
task

env MOUNTPOINT=/vagrant

script
  until mountpoint -q $MOUNTPOINT; do sleep 1; done
  /sbin/initctl emit --no-wait vagrant-mounted MOUNTPOINT=$MOUNTPOINT
end script

Create another file called /etc/init/pm2-upstart.conf

description "Start pm2 on vagrant-mounted upstart event"
author      "Me"

start on vagrant-mounted

expect fork

setgid vagrant
setuid vagrant

script
 export HOME=/home/vagrant
 sudo /usr/bin/pm2 resurrect
end script

You can now use pm2 save (alias of pm2 dump) to save the currently running process list ready to be re-started each time Vagrant is launched.

description "Start pm2 on vagrant-mounted upstart event"
author "Me"
start on vagrant-mounted
expect fork
setgid vagrant
setuid vagrant
script
export HOME=/home/vagrant
sudo /usr/bin/pm2 resurrect
end script
# workaround for https://github.com/mitchellh/vagrant/issues/6074
start on filesystem
task
env MOUNTPOINT=/vagrant
script
until mountpoint -q $MOUNTPOINT; do sleep 1; done
/sbin/initctl emit --no-wait vagrant-mounted MOUNTPOINT=$MOUNTPOINT
end script
@preeteshjain
Copy link

preeteshjain commented Feb 19, 2018

Hi Steve. Thanks for this gist. I have a question. Which one of the above solutions works as of now?

Do I have to create these 2 scripts or I can just do pm2 resurrect one time and it will be fixed for next reboots?

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