Step 1 : Install PM2 Using NPM
Use the NPM package manager to install PM2 by entering the following command in the terminal:
Step 2 : Generate a PM2 Start Script for the Init System:
PM2 is designed to operate with the default init system on a Linux system (which it can automatically detect) to produce the startup script and set up PM2 as a service that can then be restarted at system boot. Simply execute the following command as root to generate the startup script:
Step 3 : Build Node.js App
Create a new file with the name app.js in your chosen text editor. Copy and paste the following command into the file:
Save the file and exit.
Step 3 : Start Node JS Application Using PM2
Run the following command in the terminal to launch a Node JS application using PM2:
Keep in mind that when we start an application, we may also use the following extra parameters:
- Specify a name for the application: --name <app_name>
- When a file changes, your application will start itself again automatically: --watch
- An automated restart upon reaching a memory limit: --max-memory--restart <100MB>
- Specify a file for the log: --log <log_file>
- Pass added arguments to the script: -- arg1 arg2
- Delay before automatic restarts in milliseconds: --restart-delay <2000ms>
- Prefix logs with time --time
- Disabling the application to restart automatically: --no-autorestart
- A cron job pattern for an automatic restart of the application: --cron
- Disabling the application to run in a daemon process: --no-daemon
Go visit the official documentation to see all available parameters.
Step 4 : Manage the Application
Let's use the following commands in the terminal to restart, reload, stop, and delete operational processes in the Node JS application using PM2:
- The application will restart:
- The application will reload:
- The application will stop:
- The application will delete:
Conclusion
The tutorial allows anyone to quickly and effectively learn the processes of the installation and configuration of PM2 on Ubuntu 22.04.