惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
I
InfoQ
Engineering at Meta
Engineering at Meta
D
DataBreaches.Net
L
LangChain Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Recent Announcements
Recent Announcements
GbyAI
GbyAI
爱范儿
爱范儿
Microsoft Security Blog
Microsoft Security Blog
腾讯CDC
美团技术团队
罗磊的独立博客
Microsoft Azure Blog
Microsoft Azure Blog
WordPress大学
WordPress大学
T
The Blog of Author Tim Ferriss
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
雷峰网
雷峰网
M
MIT News - Artificial intelligence
D
Docker
MongoDB | Blog
MongoDB | Blog
F
Fortinet All Blogs
博客园 - 叶小钗

MDN Blog

Introducing the MDN MCP server | MDN Blog Under the hood of MDN's new frontend | MDN Blog Image formats: Codecs and compression tools | MDN Blog A beginner-friendly guide to view transitions in CSS | MDN Blog Launching MDN's new front end | MDN Blog Image formats: Pixel data from encoders to decoders | MDN Blog Celebrating 20 years of MDN | MDN Blog Image formats: Color models for humans and devices | MDN Blog Default styles for h1 elements are changing | MDN Blog Implications of Global Privacy Control | MDN Blog JavaScript Temporal is coming | MDN Blog Fix your website's Largest Contentful Paint by optimizing image loading | MDN Blog MDN 2024 content projects | MDN Blog A new learning experience on MDN | MDN Blog Countdown to the holidays with daily coding challenges | MDN Blog Monitoring and optimizing website performance | MDN Blog How to land your first developer job | MDN Blog Introducing the new MDN Community page | MDN Blog Fixing your website's JavaScript performance | MDN Blog Get back to school! Supercharge your learning with MDN and Scrimba | MDN Blog Efficient data handling with the Streams API | MDN Blog Locale-sensitive text segmentation in JavaScript with Intl.Segmenter | MDN Blog Optimize your workflow with Git stash | MDN Blog How to debug mobile apps across devices | MDN Blog Exclusive accordions using the HTML details element | MDN Blog Exploring the Broadcast Channel API for cross-tab communication | MDN Blog MDN partners with Scrimba to enhance web development learning | MDN Blog Introducing the MDN HTTP Observatory | MDN Blog Static Site Generation (SSG) with Next.js | MDN Blog New JavaScript Set methods | MDN Blog
Deploying Node.js applications with PM2 on Vultr | MDN Blog
Vultr November 8, 2023 7 minutes read · 2023-11-08 · via MDN Blog

Process Manager 2 (PM2) is an application that enables you to create persistent services for various applications, such as HTTP servers and task queue workers. PM2's cluster mode takes this functionality further by allowing you to create multiple instances of the same application for efficient resource usage. Additionally, PM2 provides a simple CLI interface for managing, scaling, and monitoring the running services.

In this article, we'll demonstrate the steps to deploy a Node.js application on a Vultr Cloud Compute server. We'll guide you through deploying a server on Vultr for your Node.js application. You'll learn to install the necessary dependencies to run your application and how to create persistent services with PM2, ensuring your application restarts automatically after a server reboot. Additionally, we'll cover setting up Nginx as a reverse proxy for efficient load balancing and securing your application with a Secure Sockets Layer (SSL) certificate to enable HTTPS.

Deploying a server on Vultr

  1. Sign up and log in to the Vultr Customer Portal.

  2. Navigate to the Products page.

  3. From the side menu, select Compute.

    Screenshot of Vultr customer portal showing the Products menu on the left with Compute as a sub option and the Deploy Server button in the center
  4. Click the Deploy Server button in the center.

  5. Select Cloud Compute as the server type.

  6. In the "Server Location" section, select the region of your choice.

  7. In the "Server Image" section, click the Marketplace Apps tab and select the NodeJS image.

    Screenshot of Vultr customer portal showing the Marketplace Apps tab, selection of the NodeJS option and the Deploy Now button on the bottom right corner

    The NodeJS Marketplace App comes pre-installed with the latest Node.js and Node Package Manager (npm) binaries, allowing you to save setup time.

  8. In the "Server Size" section, select the server size as per requirement.

  9. Select any more features as required in the "Additional Features" section.

  10. Click the Deploy Now button on the bottom right corner.

Creating a Node.js application

Having created a Vultr server as described previously, this section will guide you through creating a sample Node.js application using Express. We will walk you through initializing a Node.js project, installing Express, and creating a basic endpoint. If you already have an existing Node.js application, feel free to skip this part, clone your Git repository, and continue from the next section.

  1. Create a folder to store the project files, and navigate into it.

    mkdir ~/express-demo
    cd ~/express-demo
    
  2. Initialize a Node.js project.

  3. Install the express library.

  4. Create a file named index.js.

  5. Paste the following content into the index.js file.

    const express = require("express");
    const app = express();
    
    app.get("/", (req, res) => {
      res.send("<h1>Hello World, greetings from Vultr</h1>");
    });
    
    app.listen(3000, () => {
      console.log("Server listening on port 3000");
    });
    

    The code block above defines a basic Express-based application that displays the "Hello World, greetings from Vultr" message when you visit the home page.

  6. Save the file, and exit the editor.

  7. Allow port 3000 to listen for incoming connections.

  8. Start the application.

  9. In a web browser, navigate to the URL as shown below.

    http://SERVER_IP:3000
    

    After you confirm access, you may stop the server.

Creating a persistent service using PM2

PM2 provides an an easy-to-use CLI interface to ensure that your services are persistent, reliable, and restart automatically. In this section, you'll learn how to install the PM2 package, start your application in cluster mode, and set up a persistent service to ensure that your application starts automatically when the server boots up.

  1. Install PM2 globally. The -g flag specifies that the PM2 package should be installed globally, making it accessible to all system users.

  2. Start your Node.js application in cluster mode. Make sure to replace the path with your application's actual location. The -i flag specifies that the Node.js application should run with four instances in cluster mode.

    pm2 start ~/express-demo -i 4 --name express-demo
    
  3. Set up a persistent service.

  4. Save the configuration to apply the changes.

Configuring Nginx as a reverse proxy server

Nginx acts as a reverse proxy between your web server and clients. It directs incoming requests based on your request configuration settings. In this section, you'll learn how to configure your example application for efficient request handling and load balancing using Nginx. You'll also learn how to configure your apps for reverse proxy.

  1. Log in to the Vultr Customer Portal.

  2. Navigate to the Products page.

  3. From the side menu, expand the Network dropdown, and select DNS.

  4. Click the Add Domain button in the center.

  5. Follow the setup procedure to add your domain name by selecting the IP address of your server.

  6. Set the following hostnames as your domain's primary and secondary nameservers with your the domain registrar:

    • ns1.vultr.com
    • ns2.vultr.com
  7. Install Nginx.

  8. Create a file named express-demo.conf in the sites-available directory.

    sudo nano /etc/nginx/sites-available/express-demo.conf
    
  9. Paste the following content into the express-demo.conf file. Make sure to replace example.com with your actual domain name.

    server {
         listen 80;
         listen [::]:80;
         server_name example.com www.example.com;
    
         location / {
             proxy_pass http://127.0.0.1:3000/;
         }
    }
    

    The following directives are used in the above virtual host configuration:

    • server defines a block of settings for your domain.
    • listen instructs the server to listen on port 80 for incoming requests.
    • server_name specifies the domain names to which this server block will respond.
    • location defines what the server should do with each incoming request.
    • proxy_pass instructs the server to forward requests to another location, in this case to http://127.0.0.1:3000/.
  10. Save the file, and exit the editor.

  11. To activate the virtual host configuration, create a soft link in the sites-enabled directory.

    sudo ln -s /etc/nginx/sites-available/express-demo.conf /etc/nginx/sites-enabled/
    
  12. Test the configuration to identify the errors.

    If the configuration has no errors, your output should look like:

    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    nginx: configuration file /etc/nginx/nginx.conf test is successful
    
  13. Restart the Nginx server.

    sudo systemctl reload nginx
    
  14. Allow incoming connections on port 80.

  15. In a web browser, navigate to the URL as shown below.

    http://example.com
    
  16. Deny incoming connections on port 3000.

Installing an SSL certificate using Certbot

Certbot allows you to acquire SSL certificates from "Let's Encrypt", a free certificate authority. These SSL certificates serve as cryptographic keys that enable secure communication between a user and a web server. In this section, you'll learn how to request a free SSL certification from "Let's Encrypt" for your domain and implement HTTPS for your application. You'll also learn how to set the certificate to auto-renew before it expires in 90 days.

  1. Allow incoming connections on port 443 for HTTPS.

  2. Install the certbot package using the snap package manager.

    sudo snap install --classic certbot
    
  3. Request a new SSL certificate for your domain. Make sure to replace example.com with your actual domain name.

    sudo certbot --nginx -d example.com -d www.example.com
    
  4. In a web browser, navigate to the URL as shown below

    https://example.com
    
  5. Test that the SSL certificate auto-renews upon expiry.

    sudo certbot renew --dry-run
    

Scaling your PM2 services

In this section, you'll learn how to scale your PM2 services both up and down. Additionally, you'll explore various other PM2 commands for monitoring your application processes.

List all the PM2 processes.

Example output:

Sample output of all PM2 processes listed

Scaling down PM2 services

To scale down your Node.js application, run the pm2 scale command as shown below. Make sure to replace express-demo with your actual service name.

The above command reduces the instance count from the four instances running initially to two.

Example output:

Sample output of a table showing two instances running with a warning at the end prompting to save the list using the `pm2 save` command

Scaling up PM2 services

To scale up your Node.js/Express application, run the pm2 scale command as shown below. Make sure to replace express-demo with your actual service name.

The above command increases the instance count from the two instances running to five.

Example output:

Sample output of a table showing five instances running with a warning at the end prompting to save the list using the `pm2 save` command

Exploring additional PM2 commands

  • To stop all PM2 processes:

  • To restart all PM2 processes:

  • To soft-reload all PM2 processes:

    Soft reloading helps to minimize downtime for your Node.js/Express application by reloading instances one by one.

  • To monitor all PM2 processes:

  • To examine the logs generated by PM2:

Summary

In this article, you learned how to deploy a Node.js application using PM2 on a Vultr Cloud Compute server. The tutorial guided you through the steps to create, scale, and monitor a PM2 service. You also learned how to set up Nginx as a reverse proxy server for your PM2 service and secure it with an SSL certificate.

As an extension of your Node.js deployment, consider using a Vultr Managed Database to host the database associated with your application. It provides a secure, highly available, and easily scalable database cluster that works right out of the box.

This is a sponsored article by Vultr. Vultr is the world's largest privately-held cloud computing platform. A favorite with developers, Vultr has served over 1.5 million customers across 185 countries with flexible, scalable, global Cloud Compute, Cloud GPU, Bare Metal, and Cloud Storage solutions. Learn more about Vultr.