Skip to content

Instantly share code, notes, and snippets.

@coutinhomarco
Created June 3, 2024 21:23
Show Gist options
  • Save coutinhomarco/debe754744b816cd0a482198cda275d7 to your computer and use it in GitHub Desktop.
Save coutinhomarco/debe754744b816cd0a482198cda275d7 to your computer and use it in GitHub Desktop.

Using PM2 with DigitalOcean Droplets

Introduction

PM2 is a popular process manager for Node.js applications. It simplifies the process of running and managing applications, ensuring they stay online and perform well. DigitalOcean Droplets, on the other hand, are scalable virtual private servers that provide a reliable environment for hosting web applications.

Prerequisites

  • A DigitalOcean Droplet running Ubuntu 20.04 (or any preferred Linux distribution)
  • Node.js and npm installed on the Droplet
  • SSH access to the Droplet

Step-by-Step Guide

  1. Install PM2:

    npm install pm2@latest -g
  2. Start Your Node.js Application: Navigate to your application directory and start your application using PM2:

    pm2 start app.js --name "my-app"
  3. List Running Applications: Verify your application is running:

    pm2 list
  4. Auto-start on Reboot: Configure PM2 to start your application on system reboot:

    pm2 startup

    The command will output another command that you need to run with superuser privileges. Execute that command:

    sudo env PATH=$PATH:/usr/local/bin pm2 startup systemd -u your-username --hp /home/your-username
  5. Save the PM2 Process List: Save the current list of processes to be resurrected on reboot:

    pm2 save
  6. Monitoring and Managing Applications:

    • View application logs:
      pm2 logs
    • Stop an application:
      pm2 stop my-app
    • Restart an application:
      pm2 restart my-app

Benefits of Using PM2

  • Process Management: Simplifies starting, stopping, and monitoring Node.js applications.
  • Zero Downtime Reloads: Allows you to reload your application without downtime.
  • Log Management: Consolidates logs for easier debugging and monitoring.
  • Clustering: Supports running multiple instances of your application to take advantage of multi-core systems.

Conclusion

By using PM2 on a DigitalOcean Droplet, you can ensure your Node.js applications run smoothly and remain available. PM2's features like process management, auto-start on reboot, and monitoring make it an invaluable tool for any Node.js developer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment