Comprehensive Guide to Using PM2 for Node.js Applications - torarnehave1/slowyouio GitHub Wiki

Comprehensive Guide to Using PM2 for Node.js Applications

PM2 is a powerful process manager for Node.js applications. It provides functionality to manage the application lifecycle, including starting, stopping, monitoring, and maintaining applications across reboots. This guide will walk you through the setup and use of PM2, aimed at beginners but including some advanced features.

Step 1: Install Node.js and PM2

Before you can use PM2, you need to have Node.js and npm (Node Package Manager) installed on your system. Follow these steps to install Node.js and PM2.

Installing Node.js via NVM

NVM (Node Version Manager) allows you to manage multiple installations of Node.js and npm easily. To install NVM and Node.js, perform the following steps:

  1. Install NVM:

    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
    
    • This script downloads and installs NVM in your user directory and updates your profile to include NVM in your PATH.
  2. Activate NVM:

    source ~/.bashrc  # Or your shell's equivalent source file.
    
  3. Install Node.js:

    nvm install node  # Installs the latest version of Node.js
    
  4. Check the installation:

    node -v
    npm -v
    
    • Confirm that Node.js and npm are installed correctly.

Installing PM2

With Node.js installed, you can now install PM2 using npm.

sudo npm install pm2@latest -g  # Installs PM2 globally

Step 2: Start Your Application with PM2

Navigate to your application directory, where your Node.js application's main file (e.g., server.js) is located.

  1. Start the application:

    pm2 start server.js --name "my-application"
    
    • This command starts your application under PM2's management, naming the process "my-application".
  2. List running processes:

    pm2 list
    
    • This shows all applications currently managed by PM2.

Step 3: Advanced PM2 Management Commands

PM2 offers a wide range of commands to manage your applications effectively.

  • Monitoring: Use pm2 monit to monitor CPU and memory usage of your processes.
  • Logs: Access logs for debugging:
    pm2 logs  # Shows logs for all processes
    pm2 logs my-application  # Shows logs for a specific application
    
  • Stopping and Restarting:
    pm2 stop my-application  # Stops the specified application
    pm2 restart my-application  # Restarts the specified application
    
  • Deleting processes:
    pm2 delete my-application  # Removes the specified application from PM2's list
    

Step 4: Automate Startup with PM2

To ensure your applications start automatically after a reboot, use PM2's startup script generator.

  1. Generate a startup script:

    pm2 startup
    
    • Follow the instructions provided by PM2. It typically involves running a command provided by PM2 that sets up the startup script.
  2. Save the current process list:

    pm2 save
    
    • This ensures that the current list of running applications is restarted on boot.

Step 5: Updating PM2

To update PM2 to the latest version, run:

sudo npm install pm2@latest -g
pm2 update  # Updates in-memory PM2 processes

Conclusion

PM2 is an essential tool for Node.js application management, providing robust features to ensure your applications are running smoothly and reliably. This guide has introduced you to basic and advanced PM2 features, equipping you with the skills to use PM2 effectively in your development and production environments.

Chapter: Managing Environment Variables in PM2

In a production environment, managing configuration settings and environment variables securely and efficiently is crucial. PM2, a popular process manager for Node.js applications, provides a robust mechanism for handling environment variables through the use of environment files. This chapter delves into the setup and usage of environment files with PM2, ensuring that your applications are configured correctly without hardcoding sensitive information directly in your code or start-up scripts.

Section 1: Introduction to Environment Variables

What are Environment Variables? Environment variables are dynamic-named values stored in the system environment that are used to affect the way running processes will behave on a computer. They are particularly useful for managing application configurations separate from application logic, such as database connections, external service credentials, and deployment environments (development, production, etc.).

Section 2: Why Use PM2 for Environment Management?

PM2 streamlines the management of Node.js applications and includes support for environment variables, which can be defined globally or per application. This setup enhances security by keeping sensitive data out of the application codebase and makes it easy to update settings without code changes.

Section 3: Creating an Environment File

An environment file in PM2 is a simple JSON formatted file that specifies key-value pairs of environment variables. Here’s how to create one:

  1. Create the File:

    • Create a new file named env.json (you can name it anything but keep the .json extension for JSON format).
  2. Edit the File:

    • Open env.json in a text editor and add your environment variables as a JSON object:
      {
        "NODE_ENV": "production",
        "DB_HOST": "localhost",
        "DB_PORT": "27017",
        "DB_USER": "myUser",
        "DB_PASS": "myPassword",
        "API_KEY": "12345-abcde"
      }
      
    • Each key represents an environment variable name, and each value represents the variable's value.

Section 4: Loading Environment Variables with PM2

To load environment variables from your file during the application start-up, use the --env option with PM2:

  1. Start Application with Environment File:

    pm2 start app.js --env production
    
    • This command tells PM2 to start the app.js application and load the environment variables defined under the production property in your ecosystem configuration file or directly specified in a JSON file.
  2. Using an Ecosystem File:

    • PM2 supports the use of an ecosystem configuration file (ecosystem.config.js) which can manage more complex configurations. Here's an example:
      module.exports = {
        apps : [{
          name: "myApp",
          script: "./app.js",
          watch: true,
          env: {
            "NODE_ENV": "development",
          },
          env_production: {
            "NODE_ENV": "production",
          }
        }]
      };
      
    • Use the following command to start your application in production mode:
      pm2 start ecosystem.config.js --env production
      

Section 5: Best Practices for Managing Environment Variables with PM2

  1. Keep Secrets Out of Version Control:

    • Do not commit your environment files or ecosystem configurations containing sensitive data to version control. Use .gitignore to exclude these files.
  2. Secure Access to Environment Files:

    • Set file permissions to restrict access to your environment files so that only the necessary users and processes can read them.
  3. Regularly Update and Backup:

    • Regularly review and update the environment variables as needed. Also, ensure that you have backups of these configurations in a secure location.
  4. Audit and Monitor Usage:

    • Regularly audit the use of environment variables in your applications, especially for any signs of misuse or exposure.

Conclusion

Using PM2 with environment files provides a flexible, secure way to manage application settings across multiple development environments and production setups. By externalizing configuration settings to environment files, you can maintain a clean codebase and easily adjust settings without new deployments. This chapter has equipped you with the foundational knowledge to implement robust configuration management practices using PM2 and environment variables.