乐闻世界logo
搜索文章和话题

How to start the node.js application using pm2

1个答案

1

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:

bash
npm 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:

bash
pm2 start app.js

PM2 automatically runs your application as a background service. You can also specify a name for easier management:

bash
pm2 start app.js --name="my-app"

3. Checking Application Status After starting the application, check the status of all PM2-managed applications with:

bash
pm2 list

4. Monitoring and Logs PM2 provides real-time monitoring. View CPU and memory usage with:

bash
pm2 monit

Review application logs using:

bash
pm2 logs

For specific applications, use:

bash
pm2 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:

javascript
module.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:

bash
pm2 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.

2024年7月28日 19:44 回复

你的答案