How to use PM2 (process manager) with Strapi

How to use the PM2 process manager with Strapi

Process managers allow you to keep your Strapi application running and to reload it without downtime. The following documentation uses the PM2 process manager and describes:

  • installing PM2,
  • starting Strapi using a server.js file,
  • starting Strapi using the strapi command,
  • starting and managing Strapi using an ecosystem.config.js file.

The appropriate procedure for starting PM2 depends on the hosting provider and your application configuration.

Install PM2

Install PM2 globally:

  • With yarn:
yarn global add pm2
  • With npm:
npm install pm2 -g

Start PM2 with a server.js file

The basic usage to start an application with PM2 is to run a command such as pm2 start server.js. To configure and run your application:

  1. Create a server.js file at the application root.
  2. Add the following code snippet to the server.js file:
// path: /server.js
const strapi = require('@strapi/strapi');
const app = strapi({ distDir: './dist' });
app.start();
  1. Start the server by running pm2 start server.js in the project root directory.

Start PM2 with the strapi command

To start PM2 and your application from a terminal you should start PM2 and pass the application name and start command as arguments:

For a production environment:

  • With yarn:
pm2 start yarn --name your-app-name -- start
  • With npm:
pm2 start npm --name your-app-name -- run start

For a development environment:

  • With yarn:
pm2 start yarn --name your-app-name -- develop
  • With npm:
pm2 start npm --name your-app-name -- run develop

Start and configure PM2 with a config.js file

A PM2 configuration file allows you to save the information necessary to start your server properly at any time. This is commonly used for cloud hosting providers, where you might not have access to a terminal window to start the server. To use a configuration file:

  1. Run pm2 init at the application root to create an ecosystem.config.js file.
  2. Replace the ecosystem.config.js file content with the following code example:
  • With yarn:
// path: /ecosystem.config.js"
module.exports = {
  apps: [
    {
      name: 'app',
      script: 'yarn',
      args: 'start',
    },
  ],
};
  • With npm:
// path: .ecosystem.config.js"
module.exports = {
  apps:
    {
      name: 'app',
      script: 'npm',
      args: 'start',
    },
  ],
};
  1. Run pm2 start ecosystem.config.js to start the PM2 process.