How to Use PM2 for Running a Node.js Application in Production

You are currently viewing How to Use PM2 for Running a Node.js Application in Production

Node.js has fast become a preferred choice for developers across the globe because of its event-driven, non-blocking I/O model. However, handling production-level applications can be tricky. This is where PM2 enters the scene. PM2 is an open-source, advanced, production process manager for Node.js applications with a built-in load balancer. This blog will guide you on how to use PM2 to keep your Node.js applications up and running smoothly.

What is PM2?

PM2 is a robust, versatile, and feature-packed process manager for Node.js applications. It helps manage and keep your application online, enables you to retain the app’s state, assists with common system administration tasks, and provides a substantial amount of information about your application’s runtime.

Installing PM2

Before you install PM2, ensure you have Node.js and npm installed on your system. If not, install them first. Once that’s done, you can install PM2 globally on your system using the following npm command:

npm install pm2 -g

Running a Node.js Application with PM2

To start a Node.js application with PM2, navigate to the application directory and use the pm2 start a command followed by the entry point file name.

pm2 start app.js

Once the application starts running, PM2 will automatically assign it an App name (based on the filename, without the .js extension) and a PM2 id.

Running the npm start command with PM2

In many Node.js applications, there’s a start script specified inside the package.json file. This script often sets up some environment variables and starts the server. You might be wondering how to run this npm start command using PM2. Fortunately, PM2 makes this process straightforward.

First, navigate to the directory of your Node.js application. Then, instead of running npm start directly, you can ask PM2 to execute this command for you. Here’s how:

pm2 start npm --name "my-app" -- start

In this command:

  • pm2 start npm tells PM2 to start a process and that the process is of type npm.
  • --name "my-app" gives the process a name, which you can use for process management (stop, restart, etc.).
  • -- start is the command passed to npm, so npm knows to run its start script.

Now, PM2 will start your application and keep it running in the background. You can manage it just like any other PM2 process.

If your npm start the command requires environment variables, ensure they are set in your environment or use a package like dotenv to set them when your application starts. Alternatively, PM2 allows setting environment variables in a process file or through the command line, which can be a better choice for sensitive data.

In conclusion, PM2 makes running and managing your Node.js applications easier, even when they rely on npm start it to kick off. It provides a stable and efficient way to ensure your apps stay up and running.

Managing Application Processes

PM2 provides several commands to manage your application processes:

  • Listing all processes: pm2 list
  • Getting more details about a process: pm2 show <app_name>
  • Stopping an application: pm2 stop <app_name>
  • Restarting an application: pm2 restart <app_name>
  • Deleting an application: pm2 delete <app_name>

Key PM2 Features

Load Balancing and Cluster Mode

If you’re running applications on multi-core systems, PM2’s Cluster mode can help you utilize all available cores by spawning a process for each one. This can drastically improve the performance and reliability of your application.

To start an application in cluster mode, use the -i option followed by the number of instances you want:

pm2 start app.js -i max

The ‘max’ option will spawn as many processes as there are cores available on the machine.

Process File

For more complex applications, PM2 enables you to define the application configuration in a process file (either JavaScript, JSON, or YAML format). This allows you to specify more details about the application, such as the name, script to run, number of instances, and more.

Here’s a basic example of a process file:

jsonCopy code{
  "apps" : [{
    "name"       : "my-app",
    "script"     : "./app.js",
    "instances"  : "max",
    "exec_mode"  : "cluster"
  }]
}

You can start the application with this process file using

pm2 start process.json

Monitoring

PM2 provides a dashboard that gives you key insights about your application, like CPU usage, memory usage, request count, and more. To access it, simply use the command

pm2 monit

Log Management

Keeping track of logs is important for debugging and monitoring. PM2 aggregates all the logs from your processes and maintains them in a single file, which can be accessed using the

pm2 logs 

command.

Common mistakes in using PM2

When using PM2 to manage Node.js applications in a production environment, certain pitfalls or missteps can lead to unexpected results or inefficiencies. Here are some of the common mistakes people make:

  1. Not Using a Process File: A process file (like ecosystem.config.js) is highly recommended for production use because it allows you to store and manage your application configuration in one place. You can specify environment variables, log locations, the number of instances, and many other settings. Without it, managing these becomes a manual process and increases the chance of errors.
  2. Ignoring Log Management: PM2 handles log generation well, but if not managed, these logs can consume a lot of disk space over time. Make sure you set up log rotation, which PM2 supports via the pm2-logrotate module.
  3. Running PM2 as Root User: Running PM2 as a root user can expose your system to unnecessary risks. Instead, it’s better to run PM2 as a non-root user. If you need to run your application on a privileged port (like port 80), consider using a reverse proxy like Nginx.
  4. Not Utilizing Cluster Mode: For applications running on multi-core systems, not utilizing PM2’s cluster mode can result in inefficient use of resources. Cluster mode allows your Node.js application to be forked multiple times, taking advantage of all CPUs and automatically load-balancing incoming requests.
  5. Forgetting to Set up Startup Scripts: PM2’s processes won’t automatically start up after a system reboot unless you’ve set up startup scripts. Make sure you use the pm2 startup command to generate a startup script and ensure your applications keep running after a system restart.
  6. Not Keeping PM2 Updated: As with any package, keeping PM2 updated ensures that you benefit from the latest features, improvements, and bug fixes. Regularly check for and install updates to PM2 itself.
  7. Improper Handling of Application Crashes: Even though PM2 can restart your application if it crashes, it’s crucial to have proper error handling in your application code to understand why the crash happened in the first place. Ignoring this could lead to recurrent crashes, which could affect the performance and reliability of your application.
  8. Neglecting PM2’s Built-in Monitoring: PM2 offers a built-in application monitoring tool with pm2 monit. Ignoring this powerful tool can prevent you from identifying performance bottlenecks and potential issues in your application.

By being aware of these common mistakes, you can better utilize PM2’s full potential, ensuring your Node.js applications run efficiently and reliably in a production environment.

Conclusion

PM2 is a powerful tool that provides many critical features required for running a Node.js application in production. From handling application downtime, and clustering, to log management and monitoring, PM2 makes the entire process a lot easier and more efficient. Its simple setup and a wide array of features make it an indispensable tool for any Node.js developer.

Remember, the best way to get familiar with PM2 is by using it, so don’t hesitate to install it and try running your Node.js application. You’ll soon realize how it can simplify your production processes and take your application management to a whole new level. Happy coding!

Atiqur Rahman

I am MD. Atiqur Rahman graduated from BUET and is an AWS-certified solutions architect. I have successfully achieved 6 certifications from AWS including Cloud Practitioner, Solutions Architect, SysOps Administrator, and Developer Associate. I have more than 8 years of working experience as a DevOps engineer designing complex SAAS applications.

Leave a Reply