13

I'm developing an ExpressJS app. I use pm2 to load it:

myapp$ pm2 start bin/www

This works fine, except that adding the --watch flag doesn't seem to work; every time I change the JS source I need to explicitly restart it for my changes to take effect:

myapp$ pm2 restart www

What am I doing wrong? I've tried the --watch flag with a non-ExpressJS app and it worked as expected.

John J. Camilleri
  • 4,171
  • 5
  • 31
  • 41

4 Answers4

9

See this solution in Stack Overflow

The problem is relative to the path where pm2 is watching, and if it is relative to the execution file or the actual root path of the project.

Community
  • 1
  • 1
Kangcor
  • 1,179
  • 1
  • 16
  • 26
5

2021 Feb.

Things have changed a bit now. Gave a full example below from my project. Below works:

1 . Create config file. File: ecosystem.config.js

module.exports = {
  apps: [
    {
      name: 'api',
      script: './bin/www', // --------------- our node start script here like index.js

      // ------------------------------------ watch options - begin
      watch: ['../'],
      watch_delay: 1000,
      ignore_watch: ['node_modules'],
      watch_options: {
        followSymlinks: false,
      },
      // ------------------------------------ watch options - end

      env: {
        NODE_ENV: 'development',
        PORT: 3001,
        DEBUG: 'api:*',
        MONGODB_URI:
          'mongodb://localhost:27017/collection1?readPreference=primary&ssl=false',
      },
      env_production: {
        NODE_ENV: 'production',
      },
    },
  ],
  deploy: {
    production: {
        // user: "SSH_USERNAME",
        // host: "SSH_HOSTMACHINE",
    },
  },
};

2 . Run server (dev/ prod)

pm2 start ecosystem.config.js
pm2 start ecosystem.config.js --env production

3 . More information :

https://pm2.keymetrics.io/docs/usage/watch-and-restart/

Manohar Reddy Poreddy
  • 25,399
  • 9
  • 157
  • 140
4

I never managed to make default watch settings work in Ubuntu, however using polling via advanced watch options worked:

  "watch":  true,
  "ignore_watch" : ["node_modules"],
  "watch_options": {
    "usePolling": true,
    "interval": 1000
  }

More info:

https://github.com/buunguyen/PM2/blob/master/ADVANCED_README.md#watch--restart

https://github.com/paulmillr/chokidar#api

user3136781
  • 71
  • 1
  • 5
3

You need to specify the app location to the --watch option

myapp$ pm2 start bin/www --watch /your/location/to/app
Moh .S
  • 1,920
  • 19
  • 19