zubair1024
12/8/2019 - 2:06 PM

PM2 as a Windows Service

Running PM2 as a window service

{
  "apps": [
    {
      "name": "web",
      "script": "C:\\ws\\engineer\\titan-web\\app.js",
      "args": [],
      "cwd": "C:\\ws\\engineer\\titan-web",
      "merge_logs": true,
      "instances": 1,
      "exec_mode": "cluster_mode",
      "env": {
        "NODE_ENV": "production"
      }
    },
    {
      "name": "com",
      "script": "C:\\ws\\engineer\\titan-com\\index.js",
      "args": [],
      "cwd": "C:\\ws\\engineer\\titan-com",
      "merge_logs": true,
      "instances": 1,
      "exec_mode": "cluster_mode",
      "env": {
        "NODE_ENV": "production"
      }
    }
  ]
}

Commands to remember:

  • start/stop/list components (eg: pm2 start apps/app1.js)
  • load a predefined configuration (pm2 reload ecosystem.json.js)
  • save current configuration (pm2 save)
  • restore previously saved configuration (pm2 resurrect)
Step 1: PM2_Home

When you install PM2 (npm i -g pm2) it creates a default PM2 home folder under C:\Users\<username>\.pm2 that will store the relevant files. We will need to move that folder:

  • Create a new folder c:\etc\.pm2
  • Create a new PM2_Home variable at the System level and set the value c:\etc\.pm2
  • Restart
  • Ensure the new home directory is recognized echo %PM2_HOME%
Step 2: Make yourecosystem.json file

Your pm2 save command should help you create this or else use the file attached to this gist

  • pm2 reload ecosystem.config.js --env=production can be used to load the configuration
  • Check that your application is working as expected
  • if everything is alright, you can use pm2 save to save the configuration

If everything has been done correctly, you can test it out by:

  • Kill PM2 process pm2 kill
  • Restart PM2 process pm2 resurrect
Step 3: Use NSSM
  • Create a start up .bat file (attached to this gist). Make sure you set the correct path in the line set path=C:\Users\<username>\AppData\Roaming\npm;%path%
  • Install NSSM (beyond scope of this gist)
  • Add NSSM variable to system variable (beyond scope of this gist)
  • As Admin User, install the service nssm.exe install MyPM2Service
  • Set the Path to the bat file you had created. This should create the window service.
  • Set the Startup Type: Automatic delayed
  • Note: If you want to delete the service anytime you can run nssm.exe remove MyPM2Service

Kudos! All done! You can restart the server and test it out.

@echo off
set HOMEDRIVE=C:
set PM2_HOME=c:\etc\.pm2

@REM Ensure that pm2 command is part of your PATH variable
@REM  if you're not sure, add  it here, as follow:
set path=C:\Users\<username>\AppData\Roaming\npm;%path%

@REM Optionally, you can add 'pm2 kill' just before 
@REM  resurrect (adding a sleep between 2 commands):
@REM  	pm2 kill
@REM  	timeout /t 5 /nobreak > NUL
@REM  	pm2 resurrect
@REM otherwise, you can simple call resurrect as follow:
pm2 resurrect

echo "Done"