How to Install PM2 and Use It with an ecosystem.config.js File

PM2 is a powerful process manager for Node.js applications. It provides features for process management, monitoring, and auto-restarting applications. This guide will walk you through installing PM2 and using it with an ecosystem.config.js file for managing your Node.js applications.

1. Install PM2
Step 1: Install PM2 Globally

To install PM2 globally on your system, open your terminal and run:

npm install -g pm2


This command installs PM2 globally, making it accessible from anywhere on your system.

Step 2: Verify Installation

After installation, verify that PM2 is installed correctly by checking its version:

pm2 -v


You should see the version number of PM2 displayed.

2. Create an ecosystem.config.js File
Using an ecosystem.config.js file is a more manageable and scalable way to configure PM2 for your application. This file allows you to define how PM2 should start and manage your application.

Step 1: Create the Configuration File

In your project’s root directory, create a file named ecosystem.config.js with the following content:

module.exports = {
apps: [
{
name: 'MyExpressJSProject', // Name of your application
script: 'server.js', // Path to your main script
interpreter: './node_modules/.bin/nodemon', // Use nodemon as the interpreter if installed locally
watch: true, // Enable watching for file changes
env: {
NODE_ENV: 'development', // Environment variables for development
},
},
],
};


In this configuration:

name: The name of your application.
script: The main script to run.
interpreter: Path to nodemon if installed locally. You can adjust this if you use a globally installed nodemon.
watch: Enables automatic restarts when file changes are detected.
env: Environment variables for different environments.

Step 2: Start Your Application with PM2

To start your application using the ecosystem.config.js file, run:

pm2 start ecosystem.config.js


PM2 will read the configuration file and start your application with the specified settings.

3. Manage Your Application with PM2
Once your application is running with PM2, you can use the following commands to manage and monitor it:

View the list of processes:

pm2 list


View logs:

pm2 logs MyExpressJSProject


Stop the application:

pm2 stop MyExpressJSProject


Restart the application:

pm2 restart MyExpressJSProject


Delete the application:

pm2 delete MyExpressJSProject


Summary
PM2 is an essential tool for managing Node.js applications. By using an ecosystem.config.js file, you can efficiently configure and manage your application with PM2. This setup provides automatic restarts and process management, improving the overall development and deployment experience.

Last update on Aug 24, 2024

Tags: pm2,expressjs,server

Back to Posts

Comments

No comments yet.

ForceTeach Corporation 2024