Skip to content

Instantly share code, notes, and snippets.

@PieterScheffers
Last active November 26, 2025 09:09
Show Gist options
  • Select an option

  • Save PieterScheffers/457769f2090c6b69cd9d to your computer and use it in GitHub Desktop.

Select an option

Save PieterScheffers/457769f2090c6b69cd9d to your computer and use it in GitHub Desktop.
node.js pm2 startup script for FreeBSD
#!/bin/sh
# PM2 Startup script
# Source: https://0x0a14.de/pm2-startup-script-for-freebsd/
# Made by: Johannes Tonn
#
# Download this file
# cd /usr/local/etc/rc.d && fetch https://gist.github.com/457769f2090c6b69cd9d
#
# Make the file executable with:
# /usr/local/etc/rc.d/pm2 (chmod +x)
#
# add to /etc/rc.conf
#
# pm2_enable="YES"
# pm2_user="freebsd"
# PROVIDE: pm2
# REQUIRE: NETWORK mongod
# KEYWORD: shutdown
#
. /etc/rc.subr
name=pm2
rcvar=pm2_enable
PM2=/usr/local/lib/node_modules/pm2/bin/pm2
load_rc_config $name
start_cmd="pm2_start"
stop_cmd="pm2_stop"
restart_cmd="pm2_restart"
: ${pm2_user="freebsd"}
: ${pm2_enable="NO"}
pm2_start()
{
CMD="$PM2 resurrect"
su -l ${pm2_user} -c "${CMD}"
}
pm2_stop()
{
CMD="${PM2} dump && ${PM2} delete all && ${PM2} kill"
su -l ${pm2_user} -c "${CMD}"
}
pm2_restart()
{
CMD="pm2_stop && pm2_start"
su -l ${pm2_user} -c "${CMD}"
}
pm2_reload()
{
CMD="$PM2 reload all"
su -l ${pm2_user} -c "${CMD}"
}
run_rc_command "$1"
@dougluce
Copy link

Very handy script!

I tried stopping the daemon (with service stop pm2) before I had added any apps. It didn't actually stop. To make it work I made the further commands in the stop pipeline unconditional. I did the same for the restart pipeline. This is what I did:

--- pm2 Tue Nov 25 16:57:11 2025
***************
*** 46,58 ****

  pm2_stop()
  {
!         CMD="${PM2} dump && ${PM2} delete all && ${PM2} kill"
          su -l ${pm2_user} -c "${CMD}"
  }

  pm2_restart()
  {
!         CMD="pm2_stop && pm2_start"
          su -l ${pm2_user} -c "${CMD}"
  }

--- 46,58 ----

  pm2_stop()
  {
!         CMD="${PM2} dump ; ${PM2} delete all ; ${PM2} kill"
          su -l ${pm2_user} -c "${CMD}"
  }

  pm2_restart()
  {
!         CMD="pm2_stop ; pm2_start"
          su -l ${pm2_user} -c "${CMD}"
  }

@PieterScheffers
Copy link
Author

@dougluce Good find!

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