Deploy to the server with pm2 and custom log

Deploy to the server with pm2 and custom log

👋What is pm2

PM2 is a daemon process manager that will help you manage and keep your application online 24/7

Other features:

  • Monitoring CPU/Memory

  • The cluster mode allows networked Node.js applications (HTTP (s)/TCP/UDP server) to be scaled across all CPUs available (load balancer), without any code modifications.

  • Serve static files over HTTP

  • Manage logs easily

  • watch & restart the app on any file change

  • Startup Script Generator and that script automatically restart the service list at boot.

It is really helpful when you deploy an app to a server like AWS EC2. For example, you can use pm2 when deploy Next.js App with AWS EC2.

pm2 is written in Node.js. However, It can run any shell script or run sh, js file directly.

To install Node.js and NPM you can use fnm, then install pm2:

npm install pm2@latest -g
# or
yarn global add pm2
# or
pnpm add -g pm2

🥦Prepare an example

Create an test-pm2.js file:

let count = 0;

/**
 * Keep running 🏃 to serve.
 * Determine whether running or not by logger.
 */
const testPm2 = () => {
  setInterval(() => {
    console.log('🙏👋 from testPm2!');
  }, 1000);
};

testPm2();

🎶Using configuration file

Create an ecosystem.config.js file:

module.exports = {
  apps: [
    {
      name: 'my-app',
      script: 'test-pm2.js',
      watch: false,
      error_file: 'pm2-log/error.log',
      out_file: 'pm2-log/info.log',
      time: true,
    },
  ],
};

🪁Run

pm2 start ecosystem.config.js

View pm2-log/info.log:

View process list:

pm2 ls

Output:

Stop my-app :

pm2 stop my-app
# or stop all
pm2 stop all

# confirm
pm2 ls

To delete my-app from process management:

pm2 delete my-app
# or
pm2 delete all

# confirm
pm2 ls

For AWS CloudWatch Logs service

You have to install and configure the CloudWatch Logs agent on a running EC2 Linux instance for example. Then, you choose which files it should monitor for changes by customs the log agent configuration file:

sudo vim /opt/aws/amazon-cloudwatch-agent/bin/config.json
{
     "agent": {
         "run_as_user": "root"
     },
     "logs": {
         "logs_collected": {
             "files": {
                 "collect_list": [
                     {
                         "file_path": "/path/to/pm2-log/error.log",
                         "log_group_name": "pm2-error-log",
                         "log_stream_name": "{ec2_instance_id}"
                     },
                     {
                         "file_path": "/path/to/pm2-log/info.log",
                         "log_group_name": "pm2-info-log",
                         "log_stream_name": "{ec2_instance_id}"
                     }
                 ]
             }
         }
     }
 }

Reference