How To Use PM2

PM2 is a powerful process manager for Node.js applications, designed to help you keep your applications running smoothly in production. It provides features for process management, monitoring, and reliability. Here’s a guide on how to use PM2:

Installation:

    First, install PM2 globally using npm. Open your terminal and run:

    npm install -g pm2
    

    Starting an Application:

       To start a Node.js application with PM2, navigate to your application’s directory and run:

      pm2 start app.js   

      Replace `app.js` with the entry point of your application. PM2 will start your application and keep it running in the background.

      Listing Processes:

        To see all the processes managed by PM2, use the list command:

         pm2 list
        

        This command displays the status of each process, including details like process ID, memory usage, and uptime.

        Monitoring Applications

           PM2 provides a real-time monitoring dashboard. To access it, run:

          pm2 monit

          This will show CPU and memory usage, as well as other statistics for each process.

          Restarting and Reloading Applications

            To restart an application, use the restart command with the process ID or name

            pm2 restart app.js

            For zero-downtime reloads, which are useful for applying updates without interruption, use:

            pm2 reload app.js
            

            Stopping and Deleting Processes:

            To stop a running process, use:

            pm2 stop app.js

            To delete a process from PM2’s list, run:

            pm2 delete app.js

            Persisting Processes:

              PM2 can save the current process list and their configurations, so they restart automatically after a server reboot. Save the list with:

              pm2 save   

              To enable this feature, ensure PM2 starts on system boot by running:

                pm2 startup

              This command generates a startup script specific to your operating system.

              Managing Logs:

                PM2 simplifies log management by capturing standard output and error logs. View logs with:

                 pm2 logs

                You can also view logs for a specific application:

                pm2 logs app.js

                By using PM2, you can ensure that your Node.js applications run reliably, manage multiple processes efficiently, and monitor application performance with ease. PM2’s robust features make it an essential tool for maintaining production-level Node.js applications.