search
HomeOperation and MaintenanceNginxHow to configure Tcp load balancing in Nginx

This article uses Nginx as the proxy server for load balancing. It is just a simple application example and does not involve principles.

How to configure Tcp load balancing in Nginx

(The host here is limited, the 8000 port of the 42.192.22.128 host is used as the proxy server listening port, and 8181 is the service listening port)
The client accesses the proxy server by The proxy server distributes the request to the corresponding server.
Modify the Nginx configuration file to configure Tcp load balancing (the configuration file after Nginx installation is in /usr/local/nginx/conf/nginx.config, and the Nginx executable program is in /usr /local/nginx/sbin directory)
Add the following fields in the nginx.conf configuration file:

How to configure Tcp load balancing in Nginx

stream {
    upstream Server {
        server 42.192.22.128:8181 weight=1 max_fails=3 fail_timeout=30s;
        server 1.13.180.100:8181 weight=1 max_fails=3 fail_timeout=30s;
    }
    server {
        listen 8000;
        proxy_pass Server;
    }
}

The main thing here is Involving two configuration blocks upstream and server
defines two hosts in upstream, weight represents the weight, two The hosts are both 1, indicating that the proxy server will equally distribute client requests to the upstream server. max_fails is used in conjunction with fail_timeout, which means that within the fail_timeout time period, if If the current upstream server fails to forward more than 3 times, it is considered that the upstream server is unavailable during the current fail_timeout time period. fail_timeoutIndicates how many times the forwarding fails within this time period before the upstream server is considered temporarily unavailable.
server specifies the proxy server listening port number 8000, proxy_pass specifies the name in the upstream block Server .
After the configuration is completed, use nginx -s reload to make the running Nginx reread the configuration items and take effect.
The upstream server uses the "Swiss Army Knife" nc command to simulate the TCP server and listen on the corresponding port: (The IP address here is the intranet IP of the cloud host)

How to configure Tcp load balancing in Nginx

Use a simple Qt applet to simulate the client:

void Widget::on_btnConnection_clicked()
{
    m_pTcpSocket->connectToHost(ui->lineeditIp->text(), ui->lineeditPort->text().toUShort());
    qDebug() << m_pTcpSocket->state();
}

void Widget::on_btnSend_clicked()
{
    qDebug() << m_pTcpSocket->state();
    QByteArray byteArray;
    byteArray.append(ui->texteditMsg->toPlainText());
    const char *pChatMsg = byteArray.data();
    qDebug() << m_pTcpSocket->write(pChatMsg, byteArray.size());
}

Start two clients successively and connect to 42.192.22.128:8000 through TCP, And send the message, you can see that the message is distributed to two hosts, indicating that the client's request is indeed distributed to different servers.

How to configure Tcp load balancing in Nginx

The above is the detailed content of How to configure Tcp load balancing in Nginx. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Using NGINX: Optimizing Website Performance and ReliabilityUsing NGINX: Optimizing Website Performance and ReliabilityMay 09, 2025 am 12:19 AM

NGINX can improve website performance and reliability by: 1. Process static content as a web server; 2. forward requests as a reverse proxy server; 3. allocate requests as a load balancer; 4. Reduce backend pressure as a cache server. NGINX can significantly improve website performance through configuration optimizations such as enabling Gzip compression and adjusting connection pooling.

NGINX's Purpose: Serving Web Content and MoreNGINX's Purpose: Serving Web Content and MoreMay 08, 2025 am 12:07 AM

NGINXserveswebcontentandactsasareverseproxy,loadbalancer,andmore.1)ItefficientlyservesstaticcontentlikeHTMLandimages.2)Itfunctionsasareverseproxyandloadbalancer,distributingtrafficacrossservers.3)NGINXenhancesperformancethroughcaching.4)Itofferssecur

NGINX Unit: Streamlining Application DeploymentNGINX Unit: Streamlining Application DeploymentMay 07, 2025 am 12:08 AM

NGINXUnit simplifies application deployment with dynamic configuration and multilingual support. 1) Dynamic configuration can be modified without restarting the server. 2) Supports multiple programming languages, such as Python, PHP, and Java. 3) Adopt asynchronous non-blocking I/O model to improve high concurrency processing performance.

NGINX's Impact: Web Servers and BeyondNGINX's Impact: Web Servers and BeyondMay 06, 2025 am 12:05 AM

NGINX initially solved the C10K problem and has now developed into an all-rounder who handles load balancing, reverse proxying and API gateways. 1) It is well-known for event-driven and non-blocking architectures and is suitable for high concurrency. 2) NGINX can be used as an HTTP and reverse proxy server, supporting IMAP/POP3. 3) Its working principle is based on event-driven and asynchronous I/O models, improving performance. 4) Basic usage includes configuring virtual hosts and load balancing, and advanced usage involves complex load balancing and caching strategies. 5) Common errors include configuration syntax errors and permission issues, and debugging skills include using nginx-t command and stub_status module. 6) Performance optimization suggestions include adjusting worker parameters, using gzip compression and

Nginx Troubleshooting: Diagnosing and Resolving Common ErrorsNginx Troubleshooting: Diagnosing and Resolving Common ErrorsMay 05, 2025 am 12:09 AM

Diagnosis and solutions for common errors of Nginx include: 1. View log files, 2. Adjust configuration files, 3. Optimize performance. By analyzing logs, adjusting timeout settings and optimizing cache and load balancing, errors such as 404, 502, 504 can be effectively resolved to improve website stability and performance.

Deploying Applications with NGINX Unit: A GuideDeploying Applications with NGINX Unit: A GuideMay 04, 2025 am 12:03 AM

NGINXUnitischosenfordeployingapplicationsduetoitsflexibility,easeofuse,andabilitytohandledynamicapplications.1)ItsupportsmultipleprogramminglanguageslikePython,PHP,Node.js,andJava.2)Itallowsdynamicreconfigurationwithoutdowntime.3)ItusesJSONforconfigu

NGINX and Web Hosting: Serving Files and Managing TrafficNGINX and Web Hosting: Serving Files and Managing TrafficMay 03, 2025 am 12:14 AM

NGINX can be used to serve files and manage traffic. 1) Configure NGINX service static files: define the listening port and file directory. 2) Implement load balancing and traffic management: Use upstream module and cache policies to optimize performance.

NGINX vs. Apache: Comparing Web Server TechnologiesNGINX vs. Apache: Comparing Web Server TechnologiesMay 02, 2025 am 12:08 AM

NGINX is suitable for handling high concurrency and static content, while Apache is suitable for dynamic content and complex URL rewrites. 1.NGINX adopts an event-driven model, suitable for high concurrency. 2. Apache uses process or thread model, which is suitable for dynamic content. 3. NGINX configuration is simple, Apache configuration is complex but more flexible.

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.