search
HomeOperation and MaintenanceNginxHow to use NGINX and PM2 to optimize load balancing of VPS servers

How to use NGINX and PM2 to optimize load balancing of VPS servers

How to use NGINX and PM2 to optimize the load balancing of VPS servers

Introduction:
In modern web applications, load balancing is a very critical item technology. It can improve application scalability and reliability by spreading traffic across multiple servers. In this article, we will introduce how to use NGINX and PM2 to optimize the load balancing of VPS servers. We'll explain each step in detail with specific code examples.

Step 1: Install NGINX
First, we need to install NGINX, which is a high-performance web server and reverse proxy server. The following are the specific commands to install NGINX on Ubuntu:

$ apt-get update
$ apt-get install nginx

Step 2: Configure NGINX
Once the installation is complete, we need to do some configuration of NGINX. The following is the content of a sample configuration file:

http {
    upstream backend {
        server backend1.example.com;
        server backend2.example.com;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://backend;
        }
    }
}

In the above example, we set up a server cluster named backend, which contains two backend servers backend1.example.com and backend2.example.com. We will then listen on port 80 and proxy all traffic to the backend server cluster.

Step 3: Install PM2
Next, we need to install the PM2 process manager. PM2 can help us launch and manage Node.js applications on the server. Here are the specific commands to install PM2 on Ubuntu:

$ npm install pm2 -g

Step Four: Deploy the application on the backend server
Before we continue, we need to deploy a simple Node on the backend server. js application. The following is sample code for a simple Express application:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.send('Hello, World!');
});

app.listen(3000, () => {
    console.log('App is running on port 3000');
});

Save the above code as app.js and run the following command on the backend server to start the application:

$ node app.js

Now , our application should be accessible by visiting http://backend1.example.com:3000.

Step 5: Use PM2 to start the application on the back-end server
In order to use PM2 for process management, we need to enter the directory where the application is located and use the following command to start the application:

$ pm2 start app.js

The above command will run the application as a daemon process in the background, and automatically handle matters such as application restart and log management.

Step 6: Configure Load Balancing in NGINX
Now, we have configured NGINX and started the Node.js application on the backend server. We need to modify the NGINX configuration file to achieve load balancing. The following is the content of the modified sample configuration file:

http {
    upstream backend {
        server backend1.example.com:3000;
        server backend2.example.com:3000;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://backend;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
}

In the above configuration file, we changed the port of the backend server from 80 to 3000, and added the proxy_set_header directive to pass some key HTTP header information.

Step 7: Restart NGINX and PM2 services
Before we perform load balancing testing, we need to restart NGINX and PM2 services for the changes to take effect. The following is the restart command:

$ service nginx restart
$ pm2 restart all

Step 8: Test load balancing
Now, we can use a web browser or the curl command to test whether the load balancing is working properly. We should be able to get a "Hello, World!" response by visiting http://yourdomain.com. Every time we refresh the page, we should see different server names for the backend servers, which means load balancing is in effect.

Conclusion:
By using NGINX and PM2, we can easily achieve load balancing on the VPS server. Load balancing can improve the scalability and reliability of applications to better serve users. We hope that the specific code examples and steps provided in this article can help readers better practice server optimization and load balancing.

The above is the detailed content of How to use NGINX and PM2 to optimize load balancing of VPS servers. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
NGINX Unit's Purpose: Running Web ApplicationsNGINX Unit's Purpose: Running Web ApplicationsApr 30, 2025 am 12:06 AM

The purpose of NGINXUnit is to simplify the deployment and management of web applications. Its advantages include: 1) Supports multiple programming languages, such as Python, PHP, Go, Java and Node.js; 2) Provides dynamic configuration and automatic reloading functions; 3) manages application lifecycle through a unified API; 4) Adopt an asynchronous I/O model to support high concurrency and load balancing.

NGINX: An Introduction to the High-Performance Web ServerNGINX: An Introduction to the High-Performance Web ServerApr 29, 2025 am 12:02 AM

NGINX started in 2002 and was developed by IgorSysoev to solve the C10k problem. 1.NGINX is a high-performance web server, an event-driven asynchronous architecture, suitable for high concurrency. 2. Provide advanced functions such as reverse proxy, load balancing and caching to improve system performance and reliability. 3. Optimization techniques include adjusting the number of worker processes, enabling Gzip compression, using HTTP/2 and security configuration.

NGINX vs. Apache: A Look at Their ArchitecturesNGINX vs. Apache: A Look at Their ArchitecturesApr 28, 2025 am 12:13 AM

The main architecture difference between NGINX and Apache is that NGINX adopts event-driven, asynchronous non-blocking model, while Apache uses process or thread model. 1) NGINX efficiently handles high-concurrent connections through event loops and I/O multiplexing mechanisms, suitable for static content and reverse proxy. 2) Apache adopts a multi-process or multi-threaded model, which is highly stable but has high resource consumption, and is suitable for scenarios where rich module expansion is required.

NGINX vs. Apache: Examining the Pros and ConsNGINX vs. Apache: Examining the Pros and ConsApr 27, 2025 am 12:05 AM

NGINX is suitable for handling high concurrent and static content, while Apache is suitable for complex configurations and dynamic content. 1. NGINX efficiently handles concurrent connections, suitable for high-traffic scenarios, but requires additional configuration when processing dynamic content. 2. Apache provides rich modules and flexible configurations, which are suitable for complex needs, but have poor high concurrency performance.

NGINX and Apache: Understanding the Key DifferencesNGINX and Apache: Understanding the Key DifferencesApr 26, 2025 am 12:01 AM

NGINX and Apache each have their own advantages and disadvantages, and the choice should be based on specific needs. 1.NGINX is suitable for high concurrency scenarios because of its asynchronous non-blocking architecture. 2. Apache is suitable for low-concurrency scenarios that require complex configurations, because of its modular design.

NGINX Unit: Key Features and CapabilitiesNGINX Unit: Key Features and CapabilitiesApr 25, 2025 am 12:17 AM

NGINXUnit is an open source application server that supports multiple programming languages ​​and provides functions such as dynamic configuration, zero downtime updates and built-in load balancing. 1. Dynamic configuration: You can modify the configuration without restarting. 2. Multilingual support: compatible with Python, Go, Java, PHP, etc. 3. Zero downtime update: Supports application updates that do not interrupt services. 4. Built-in load balancing: Requests can be distributed to multiple application instances.

NGINX Unit vs. Other Application ServersNGINX Unit vs. Other Application ServersApr 24, 2025 am 12:14 AM

NGINXUnit is better than ApacheTomcat, Gunicorn and Node.js built-in HTTP servers, suitable for multilingual projects and dynamic configuration requirements. 1) Supports multiple programming languages, 2) Provides dynamic configuration reloading, 3) Built-in load balancing function, suitable for projects that require high scalability and reliability.

NGINX Unit: The Architecture and How It WorksNGINX Unit: The Architecture and How It WorksApr 23, 2025 am 12:18 AM

NGINXUnit improves application performance and manageability with its modular architecture and dynamic reconfiguration capabilities. 1) Modular design includes master processes, routers and application processes, supporting efficient management and expansion. 2) Dynamic reconfiguration allows seamless update of configuration at runtime, suitable for CI/CD environments. 3) Multilingual support is implemented through dynamic loading of language runtime, improving development flexibility. 4) High performance is achieved through event-driven models and asynchronous I/O, and remains efficient even under high concurrency. 5) Security is improved by isolating application processes and reducing the mutual influence between applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function