How to watch and reload an ExpressJS app with pm2
Asked Answered
D

4

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.

Drawplate answered 13/2, 2015 at 14:37 Comment(1)
pm2 start app.js --watchHindi
P
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.

Pennypennyaliner answered 13/2, 2015 at 14:57 Comment(0)
P
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/

Phocaea answered 21/2, 2021 at 6:4 Comment(0)
T
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

Tenet answered 13/12, 2021 at 4:42 Comment(1)
this solution is working perfectly in my caseShumway
J
3

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

myapp$ pm2 start bin/www --watch /your/location/to/app
Jane answered 12/4, 2018 at 6:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.