Steps to Start a Node.js Application with PM2
1. Installing PM2 First, ensure that Node.js and npm (Node Package Manager) are installed on your machine. Then, install PM2 using npm:
bashnpm install pm2@latest -g
This command globally installs PM2, enabling you to use it from anywhere.
2. Starting the Application
Once PM2 is installed, you can start your Node.js application. Assuming your entry file is app.js, use the following command:
bashpm2 start app.js
PM2 automatically runs your application as a background service. You can also specify a name for easier management:
bashpm2 start app.js --name="my-app"
3. Checking Application Status After starting the application, check the status of all PM2-managed applications with:
bashpm2 list
4. Monitoring and Logs PM2 provides real-time monitoring. View CPU and memory usage with:
bashpm2 monit
Review application logs using:
bashpm2 logs
For specific applications, use:
bashpm2 logs my-app
5. Starting with Configuration File
For complex setups, configure your application using JSON or YAML files. For example, create ecosystem.config.js:
javascriptmodule.exports = { apps: [{ name: "my-app", script: "app.js", instances: 4, exec_mode: "cluster", env: { NODE_ENV: "development", }, env_production: { NODE_ENV: "production", } }] };
Start the application with:
bashpm2 start ecosystem.config.js
Conclusion
PM2 not only manages Node.js applications but also offers advanced features like load balancing and log management, making it ideal for production environments. With PM2, you can ensure high availability and easily implement zero-downtime updates.