Pm2 перезапуск при ошибке

I have a Node.js app ready which is workable, but has known and unknown bugs which crash the app. In such cases it would be nice if pm2 can restart the node app. Is this feature already available in pm2?

asked Oct 1, 2014 at 6:29

Talespin_Kit's user avatar

Talespin_KitTalespin_Kit

20.9k29 gold badges89 silver badges135 bronze badges

Yes, it does this by default. For more information see Restart strategies.

If the app repeatedly fails to start over a short period of time, pm2 may cease restarting. See configuration, min_uptime and max_restarts.

answered Oct 1, 2014 at 6:57

jgillich's user avatar

14

Also, check this new excellent option:

--exp-backoff-restart-delay=100

pm2 will restart the crashed app after 100 milliseconds (0.1 seconds), then step-by-step increase restart-delay to 15 seconds.

answered May 7, 2019 at 12:55

xoid's user avatar

xoidxoid

1,1241 gold badge10 silver badges24 bronze badges

To make app restart when it crashes you have to use one of PM2’s restart strategies.

There is something called «Exponential Backoff Restart Delay» which PM2 explains as:

Instead of restarting your application like crazy when exceptions happens (e.g. database is down), the exponential backoff restart will increase incrementaly the time between restarts.

You can set it using the CLI like this:

pm2 start app.js --exp-backoff-restart-delay=100

There are other restart methods also, which are mentioned here.

answered Mar 24, 2020 at 10:14

illiteratewriter's user avatar

illiteratewriterilliteratewriter

4,0751 gold badge23 silver badges45 bronze badges

This may help:

# Generate Startup Script
$ pm2 startup

# Freeze your process list across server restart
$ pm2 save

# Remove Startup Script
$ pm2 unstartup

More details here

answered Oct 9, 2019 at 14:48

Alliswell's user avatar

AlliswellAlliswell

1,52320 silver badges35 bronze badges

Restart strategies

When starting application with PM2, applications are automatically restarted on auto exit, event loop empty (node.js) or when application crash.
But you can also configure extra restart strategies like:

  • Restart app at a specified CRON time
  • Restart app when files have changed
  • Restart when app reach a memory threshold
  • Delay a start and automatic restart
  • Disable auto restart (apps are always restarted with PM2 when crashing or exiting by default)
  • Restart application automatically at a specific exponential increasing time

Restart at cron time

Via CLI:

$ pm2 start app.js --cron-restart="0 0 * * *"
# Or when restarting an app
$ pm2 restart app --cron-restart="0 0 * * *"

Via configuration file, use the cron_restart attribute:

module.exports = {
  apps : [{
    name: 'Business News Watcher',
    script: 'app.js',
    instances: 1,
    cron_restart: '0 0 * * *',
    env: {
      NODE_ENV: 'development'
    },
    env_production: {
      NODE_ENV: 'production'
    }
  }]
}

To disable cron restart:

pm2 restart app --cron-restart 0

Restart on file change

PM2 can automatically restart your application when a file is modified in the current directory or its subdirectories:

Via CLI:

$ pm2 start app.js --watch

Note: If an application is started with the --watch option, stopping the app will not prevent it to be restarted on file change.
To totally disable the watch feature, do: pm2 stop app --watch or toggle the watch option on application restart via pm2 restart app --watch.

Via configuration file, use the watch: true attribute:

module.exports = {
  script: "app.js",
  watch: true
}

You can specify which folder to watch for change, ignore folder and watch files interval with these options:

module.exports = {
  script: "app.js",
  // Specify which folder to watch
  watch: ["server", "client"],
  // Specify delay between watch interval
  watch_delay: 1000,
  // Specify which folder to ignore 
  ignore_watch : ["node_modules", "client/img"],
}

Memory based restart strategy

PM2 allows to reload (auto fallback to restart if not in cluster) an application based on a memory limit/ Please note that the PM2 internal worker (which checks memory), starts every 30 seconds, so you may have to wait a bit before your process gets restarted automatically after reaching the memory threshold.

CLI:

$ pm2 start api.js --max-memory-restart 300M

Via configuration file, use the max_memory_restart attribute:

module.exports = {
  script: 'api.js',
  max_memory_restart: '300M'
}

Note: Units can be K(ilobyte) (e.g. 512K), M(egabyte) (e.g. 128M), G(igabyte) (e.g. 1G).

Restart Delay

Set a delay between auto restart with the Restart Delay strategy:

CLI:

$ pm2 start app.js --restart-delay=3000

Via configuration file, use the restart_delay attribute:

module.exports = {
  script: 'app.js',
  restart_delay: 3000
}

No Auto Restart

This is useful in case we wish to run 1-time scripts and don’t want the process manager to restart our script in case it’s completed running.

CLI:

$ pm2 start app.js --no-autorestart

Via configuration file, use the autorestart attribute:

module.exports = {
  script: 'app.js',
  autorestart: false
}

Skip Auto Restart For Specific Exit Codes

Sometimes you might want the application to automatically restart in case of failure (i.e. non-zero exit code),
while not wanting the process manager to restart it when it shuts down properly (i.e. exit code equal to 0).

In this case, you can still use PM2 just fine with a stop_exit_codes option set to exit codes that should skip auto restart:

CLI:

$ pm2 start app.js --stop-exit-codes 0

Or via configuration file, use the stop_exit_codes attribute:

module.exports = [{
  script: 'app.js',
  stop_exit_codes: [0]
}]

Exponential Backoff Restart Delay

A new restart mode has been implemented on PM2 Runtime, making your application restarts in a smarter way. Instead of restarting your application like crazy when exceptions happens (e.g. database is down), the exponential backoff restart will increase incrementally the time between restarts, reducing the pressure on your DB or your external provider… Pretty easy to use:

CLI:

$ pm2 start app.js --exp-backoff-restart-delay=100

Via configuration file, use the exp_backoff_restart_delay attribute:

module.exports = {
  script: 'app.js',
  exp_backoff_restart_delay: 100
}

When an application crash unexpectedly and the option --exp-backoff-restart-delay is activated, you will be able to see a new application status waiting restart.

By running pm2 logs you will also see the restart delay being incremented:

PM2      | App [throw:0] will restart in 100ms
PM2      | App [throw:0] exited with code [1] via signal [SIGINT]
PM2      | App [throw:0] will restart in 150ms
PM2      | App [throw:0] exited with code [1] via signal [SIGINT]
PM2      | App [throw:0] will restart in 225ms

As you can see the restart delay between restarts will increase in an exponential moving average, till reaching the maximum of 15000ms between restarts.

When the application will then get back to a stable mode (uptime without restarts of more than 30 seconds), the restart delay will automatically reset to 0ms.

Contribute to this page

Exponential Backoff Restart Delay

Available in PM2 >= 3.2

A new restart mode has been implemented on PM2 Runtime, making your application restarts in a smarter way. Instead of restarting your application like crazy when exceptions happens (e.g. database is down), the exponential backoff restart will increase incrementaly the time between restarts, reducing the pressure on your DB or your external provider… Pretty easy to use:

CLI:

$ pm2 start app.js --exp-backoff-restart-delay=100

Or via ecosystem.config.js file:

module.exports = [{
  script: 'app.js',
  exp_backoff_restart_delay: 100
}]

When an application crash unexpectedly and the option --exp-backoff-restart-delay is activated, you will be able to see a new application status waiting restart.

By running pm2 logs you will also see the restart delay being incremented:

PM2      | App [throw:0] will restart in 100ms
PM2      | App [throw:0] exited with code [1] via signal [SIGINT]
PM2      | App [throw:0] will restart in 150ms
PM2      | App [throw:0] exited with code [1] via signal [SIGINT]
PM2      | App [throw:0] will restart in 225ms

As you can see the restart delay between restarts will increase in an exponential moving average, till reaching the maximum of 15000ms between restarts.

When the application will then get back to a stable mode (uptime without restarts of more than 30 seconds), the restart delay will automatically reset to 0ms.

Fixed Restart Delay

Available in PM2 >= 0.9

You can also use the restart_delay to set a fixed timing between restarts:

CLI:

$ pm2 start app.js --restart-delay=3000

Or via ecosystem.config.js file:

module.exports = [{
  script: 'app.js',
  restart_delay: 3000
}]

Memory based reload strategy

Checkout https://pm2.io/docs/docs/runtime/features/memory-limit/

0second Downtime Reload

Checkout the cluster mode to get this behavior

No Auto Restart

This is useful in case we wish to run 1-time scripts and don’t want the process manager to restart our script in case it’s completed running.

Simply running these scripts from bash would terminate the script in case the ssh-session is terminated and the script should not get restarted when it completes execution.

PM2 is perfect for such cases, providing robust monitoring and logging

CLI:

$ pm2 start app.js --no-autorestart

I have a Node.js app ready which is workable, but has known and unknown bugs which crash the app. In such cases it would be nice if pm2 can restart the node app. Is this feature already available in pm2?

asked Oct 1, 2014 at 6:29

Talespin_Kit's user avatar

Talespin_KitTalespin_Kit

20.9k29 gold badges89 silver badges135 bronze badges

Yes, it does this by default. For more information see Restart strategies.

If the app repeatedly fails to start over a short period of time, pm2 may cease restarting. See configuration, min_uptime and max_restarts.

answered Oct 1, 2014 at 6:57

jgillich's user avatar

14

Also, check this new excellent option:

--exp-backoff-restart-delay=100

pm2 will restart the crashed app after 100 milliseconds (0.1 seconds), then step-by-step increase restart-delay to 15 seconds.

answered May 7, 2019 at 12:55

xoid's user avatar

xoidxoid

1,1241 gold badge10 silver badges24 bronze badges

To make app restart when it crashes you have to use one of PM2’s restart strategies.

There is something called «Exponential Backoff Restart Delay» which PM2 explains as:

Instead of restarting your application like crazy when exceptions happens (e.g. database is down), the exponential backoff restart will increase incrementaly the time between restarts.

You can set it using the CLI like this:

pm2 start app.js --exp-backoff-restart-delay=100

There are other restart methods also, which are mentioned here.

answered Mar 24, 2020 at 10:14

illiteratewriter's user avatar

illiteratewriterilliteratewriter

4,0751 gold badge23 silver badges45 bronze badges

This may help:

# Generate Startup Script
$ pm2 startup

# Freeze your process list across server restart
$ pm2 save

# Remove Startup Script
$ pm2 unstartup

More details here

answered Oct 9, 2019 at 14:48

Alliswell's user avatar

AlliswellAlliswell

1,52320 silver badges35 bronze badges

In this article, we are going to learn, about restarting a Node.js application when an uncaught exception happens. For this, we are going to use the pm2 module.

Approach: Let’s see the approach step by step:

  • Step 1: Install the pm2 module and use it to start the server.
  • Step 2: When an uncaught exception happens, then execute the command process.exit() to stop the server.
  • Step 3: Then, pm2 module will automatically start the server again.

process.exit() stop the server and pm2 force it to start. In this way, the server will restart.

Implementation: Below is the step-by-step implementation of the above approach.

Step 1: Initializes NPM: Create and Locate your project folder in the terminal & type the command

npm init -y

It initializes our node application & makes a package.json file.

Step 2: Install Dependencies: Locate your root project directory into the terminal and type the command

npm install express pm2

To install express and pm2 as dependencies inside your project

Step 3: Creating a list of products: Let’s create an array of products and set it to constant products.

const products = [];

Step 4: Creating Routes for the home page and the products page: Let’s create two routes so that users can access the home page and the products page.

app.get('/', (req, res) => {
   res.send('Hello Geeks!');
});

app.get('/products', (req, res) => {
   if (products.length === 0) {
       res.send('No products found!');
       process.exit();
   } else {
       res.json(products);
   }
});

Inside the product route, we use process.exit() method to stop the server.

Complete Code:

Javascript

const express = require('express');

const app = express();

const products = [];

app.get('/', (req, res) => {

    res.send('Hello Geeks!');

});

app.get('/products', (req, res) => {

    if (products.length === 0) {

        res.send('No products found!');

        process.exit();

    } else {

        res.json(products);

    }

});

app.listen(3000, ()=>{

    console.log('listening on port 3000');

});

Steps to run the application: Inside the terminal type the command to run your script ‘app.js’ with pm2.

pm2 start app.js

Output:

Last Updated :
18 Jul, 2022

Like Article

Save Article

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Pm filter monitoring ошибка
  • Po102 ошибка ваз 2114
  • Pluto b46 v2 ошибки
  • Po102 ошибка ваз 2110
  • Pluginobject is undefined ошибка при подписании

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии