How to Manage Node Applications with PM2?
PM2 is a process manager for Node.js applications. It helps keep apps running smoothly by automatically restarting them if they crash. Also, you can manage multiple applications, which is a great aspect for production environments.
Furthermore, PM2 provides built-in monitoring tools to display logs, CPU, and memory usage. Thus, you can identify performance issues early. Also, you can configure PM2 to start applications on system boot. They restart automatically after a reboot. All in all, PM2 makes Node.js app management super-simple and improves reliability in production.
Let’s learn how to do that with this simple guide.
Prerequisites
The system can be macOS, Linux, or Windows. Your system must have Node.js and NPM installed before PM2 installation. Also, you must log in to your server as the root user before proceeding.
=> Use the NPM package manager to install PM2 and run the following command in your terminal to install it globally on your system –
npm install pm2 -g
Creating a Sample Node.js Application (Optional)
You can skip these steps if the Node.js application is ready. Or else, you can create a simple example application.
=> Open a text editor of your liking and create a new file named app.js. Copy and paste the following code into it.
The script below sets up a basic HTTP server that listens on port 80 and responds with “Cantech Web Hosting” when accessed.
const http = require('http'); const hostname = '0.0.0.0'; const port = 80; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Cantech Web Hosting'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
Next, save the file and exit the editor.
Running the Application with PM2
The below command will start your Node.js application using PM2 –
pm2 start app.js
** Replace app.js with the correct filename (in case of application having a different entry file).
You can use various options with PM2 while starting an application. Some useful parameters are listed below –
- –name <app_name> sets a custom name for the application.
- –watch automatically restarts the application when a file changes.
- –max-memory-restart <100MB> restarts the app when memory usage crosses a limit.
- –log <log_file> helps specify a log file.
- –restart-delay <2000ms> sets a delay before automatic restarts.
- –no-autorestart prevents automatic restarts.
- –cron restarts applications on a schedule.
- –no-daemon to run the application in the foreground and not in daemon process.
** You can check PM2’s official documentation for more available options.
Managing the Application
You can easily manage your application with it once it is running.
Restart the application using –
pm2 restart app
Reload the application without downtime with the below command –
pm2 reload app
Run the below and stop the application –
pm2 stop app
Remove the application from PM2’s process list using –
pm2 delete app
Viewing All Running Applications
Use the below command to check all applications that PM2 currently manages –
pm2 list
Checking Logs
With the below command, view real-time logs of an application –
pm2 logs
Also, view older logs with a specific number of lines with –
pm2 logs --lines 200
Monitoring Resource Usage
PM2’s built-in monitoring tool can track the CPU and memory usage of your applications. Run the following command for the same –
pm2 monit
Setting Up a Web-Based Dashboard
PM2 comes with a web-based dashboard to monitor and manage applications visually. Enable it easily with –
pm2 plus
The command will ask if you have a PM2 account. Log in with your credentials if you have one. Otherwise, create a new account and accept the license agreement.
After that, PM2 will display a web link to access the dashboard. Open the link in your browser and log in with your account.
Configuring PM2 to Start on Boot
To make sure PM2 starts automatically when the system reboots, you need to generate a startup script. Run the following command –
pm2 startup
In case you want to disable PM2 from starting on boot later, run –
pm2 unstartup systemd
Saving Applications for Automatic Restart
Save your applications to a PM2 process list so that they restart automatically after a reboot.
pm2 save
You can manually restore them by running the below if your applications do not restart automatically.
pm2 resurrect
Updating PM2
Check for updates by listing outdated global NPM packages –
npm outdated -g
Install the latest version if PM2 appears in the list.
npm install pm2@latest -g
Refresh the PM2 process list after an update.
pm2 update
Best Practices and Security Considerations
Using Cluster Mode for Zero Downtime
The brief downtime when an application restarts can be prevented with PM2’s cluster mode. It runs multiple instances of your application so that one instance can restart while the others keep running.
The below command stops an application before enabling cluster mode –
pm2 stop app
An application can start in cluster mode with multiple instances with –
pm2 start app.js -i 3
Scale an existing application and increase the number of instances using –
pm2 scale app 4
Implementing Graceful Shutdown
Your application finishes all active tasks before stopping with a graceful shutdown. This prevents issues such as incomplete HTTP requests or database disconnections.
PM2 sends a SIGINT signal before stopping an application. You can handle this signal in your application with the following code. This code logs a message, stops the HTTP server, and then exits the process safely.
process.on('SIGINT', function() { console.log('Shutdown signal intercepted'); server.close(); process.exit(); });
You can visit the official documentation and learn various other aspects about PM2.