DEV Community

Christopher
Christopher

Posted on

How to build a startup service for Node.js server (DEAD SIMPLE)

Here is your text converted into rich text format:


How to build a startup service for Node.js server (DEAD SIMPLE)

September 30th, 2024 06:11

Tags: [work] [4 - Indexes/Computer Science | Computer Science] [system design]

If you just want an easy way to ensure that your Node.js app stays running no matter what, you came to the right place. This guide will ensure that you have a reliable auto-running Node.js backend for your full stack application.

1. Install pm2

Run the following command:

npm install -g pm2
Enter fullscreen mode Exit fullscreen mode

Afterwards, verify the installation:

pm2 --version
Enter fullscreen mode Exit fullscreen mode

Once you've verified the installation, go into the root of your Node.js project and add a file called ecosystem.config.js. This will be what pm2 uses to start up the Node backend automatically.

ecosystem.config.js

module.exports = {
  apps: [
    {
      name: 'rcm-server',
      script: 'npm',
      args: 'start',
      watch: true,
      env: {
        NODE_ENV: 'production',
      },
    },
  ],
};
Enter fullscreen mode Exit fullscreen mode

2. Start pm2 service

Run the following command to bind your app's process to pm2:

pm2 start ecosystem.config.js
Enter fullscreen mode Exit fullscreen mode

Then:

pm2 startup
Enter fullscreen mode Exit fullscreen mode

And finally:

pm2 save
Enter fullscreen mode Exit fullscreen mode

Be sure to run any output command it tells you to ensure it gets saved in pm2/dump.pm2

That's it. Really.

Top comments (0)