How to use the PM2 process manager with Strapi
The content of this page might not be fully up-to-date with Strapi 5 yet.
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:
- yarn
- npm
yarn global add pm2
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:
- Create a
server.js
file at the application root. - Add the following code snippet to the
server.js
file:
- JavaScript
- TypeScript
const strapi = require('@strapi/strapi');
strapi().start();
const strapi = require('@strapi/strapi');
const app = strapi({ distDir: './dist' });
app.start();
- Start the server by running
pm2 start server.js
in the project root directory.
TypeScript projects require additional code in the server.js
file to identify the correct directory. See the previous TypeScript code example or the TypeScript documentation for additional details.
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:
- yarn
- npm
pm2 start yarn --name app -- start
pm2 start npm --name app -- run start
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:
- Run
pm2 init
at the application root to create anecosystem.config.js
file. - Replace the
ecosystem.config.js
file content with the following code example:
- yarn
- npm
module.exports = {
apps: [
{
name: 'app',
script: 'yarn',
args: 'start',
},
],
};
module.exports = {
apps: [
{
name: 'app',
script: 'npm',
args: 'start',
},
],
};
- Run
pm2 start ecosystem.config.js
to start the PM2 process.
The ecosystem.config.js
code example is the minimum configuration. The PM2 ecosystem file documentation provides all of the configuration options.