start pm2 node process with flags
How to Start PM2 Node Process with Flags
If you are a developer who frequently works with Node.js and needs to manage multiple processes, PM2 is a great tool to help you monitor and control your applications. In this tutorial, I will show you how to start a PM2 node process with flags.
Step 1: Install PM2
The first step is to install PM2 on your system. You can do this by running the following command:
npm install pm2 -g
Step 2: Create a Node.js Application
Next, create a simple Node.js application that you want to run using PM2. You can create a new file called app.js and add the following code:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Step 3: Start PM2 with Flags
Now that you have your Node.js application ready, you can start it using PM2. You can pass flags to the pm2 start command to customize the behavior of the process. Here are some common flags you may want to use:
- --name: set a custom name for the process
- --watch: watch for file changes and automatically restart the process
- --max-restarts: set the maximum number of times the process can be restarted
- --log-date-format: set the format of the timestamp in the log files
To start your Node.js application with PM2 and pass flags, run the following command:
pm2 start app.js --name myapp --watch --max-restarts=3 --log-date-format "YYYY-MM-DD HH:mm Z"
This will start your Node.js application with the name "myapp", watch for file changes, allow a maximum of 3 restarts, and use the "YYYY-MM-DD HH:mm Z" format for the timestamp in the log files.
Alternative Method
Another way to start a PM2 node process with flags is to create a configuration file. You can create a file called ecosystem.config.js and add the following code:
module.exports = {
apps : [{
name: "myapp",
script: "./app.js",
watch: true,
max_restarts: 3,
log_date_format: "YYYY-MM-DD HH:mm Z"
}]
}
Then, you can start your Node.js application with PM2 using the following command:
pm2 start ecosystem.config.js
This will start your Node.js application with the same flags as before, but using a configuration file instead of passing flags directly to the pm2 start command.