search
HomeOperation and MaintenanceNginxHow to configure TCP load balancing in Nginx

How to configure TCP load balancing in Nginx

May 19, 2023 am 08:29 AM
nginxtcp

How to configure TCP load balancing in Nginx

Assuming that the Kubernetes cluster has been configured, we will create a virtual machine for Nginx based on CentOS.

The following are the details of the settings in the experiment:

  • Nginx (CenOS8 Minimal) – 192.168.1.50

  • Kube Master – 192.168.1.40

  • Kube Worker 1 – 192.168.1.41

  • ##Kube Worker 2 – 192.168.1.42

Step 1) Install the epel warehouse

Because the nginx software package is not in the default warehouse of the CentOS system, you need to install the epel warehouse:

[root@nginxlb ~]# dnf install epel-release -y

Step 2) Install Nginx

Run the following command to install nginx:

[root@nginxlb ~]# dnf install nginx -y

Use the rpm command to verify the details of the Nginx package:

[root@nginxlb ~]# rpm -qi nginx

How to configure TCP load balancing in Nginx

Configure the firewall to allow access to nginx's http and https services:

[root@nginxlb ~]# firewall-cmd --permanent --add-service=http[root@nginxlb ~]# firewall-cmd --permanent --add-service=https[root@nginxlb ~]# firewall-cmd –reload

Use the following command to set SELinux to permissive mode, and restart the system to make selinux shutdown take effect:

[root@nginxlb ~]# sed -i s/^SELINUX=.*$/SELINUX=permissive/ /etc/selinux/config[root@nginxlb ~]# reboot

Step 3) Get the application’s NodePort details from Kubernetes

[kadmin@k8s-master ~]$  kubectl get all -n ingress-nginx

How to configure TCP load balancing in Nginx

As you can see from the above output, each worker node’s NodePort 32760 is mapped to port 80 and NodePort 32375 is mapped to port 443. We will use these node ports in the Nginx configuration file for load balancing.

Step 4) Configure Nginx for load balancing

Edit the nginx configuration file and add the following:

[root@nginxlb ~]# vim /etc/nginx/nginx.conf

Comment out the "server" part ( From lines 38 to 57):

How to configure TCP load balancing in Nginx

And add the following lines:

upstream backend {
  server 192.168.1.41:32760;
  server 192.168.1.42:32760;
}

server {
  listen 80;
  location / {
      proxy_read_timeout 1800;
      proxy_connect_timeout 1800;
      proxy_send_timeout 1800;
      send_timeout 1800;
      proxy_set_header        Accept-Encoding   "";
      proxy_set_header        X-Forwarded-By    $server_addr:$server_port;
      proxy_set_header        X-Forwarded-For   $remote_addr;
      proxy_set_header        X-Forwarded-Proto $scheme;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_pass http://backend;
  }

   location /nginx_status {
       stub_status;
   }
}

How to configure TCP load balancing in Nginx

Save the configuration file and exit.

How to configure TCP load balancing in Nginx

According to the above changes, all requests to port 80 of nginx will be routed to the NodePort (32760) of the Kubernetes worker nodes (192.168.1.41 and 192.168.1.42) ) port.

Use the following command to enable the Nginx service:

[root@nginxlb ~]# systemctl start nginx[root@nginxlb ~]# systemctl enable nginx

Test Nginx’s TCP load balancer

To test whether nginx works as a TCP load balancer for Kubernetes Normal, please deploy a deployment based on nginx, expose the deployment port as port 80, and define the entry resource for the nginx deployment. I have used the following commands to deploy these Kubernetes objects:

[kadmin@k8s-master ~]$ kubectl create deployment nginx-deployment --image=nginx
deployment.apps/nginx-deployment created
[kadmin@k8s-master ~]$ kubectl expose deployments nginx-deployment  --name=nginx-deployment --type=NodePort --port=80
service/nginx-deployment exposed

Run the following commands to get the deployments, svc and ingress details:

How to configure TCP load balancing in Nginx

Update the hosts file of the local host so that nginx- lb.example.com points to the IP address of the nginx server (192.168.1.50)

[root@localhost ~]# echo "192.168.1.50  nginx-lb.example.com" >> /etc/hosts

Try to access nginx-lb.example.com through the browser

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
NGINX's Key Features: Performance, Scalability, and SecurityNGINX's Key Features: Performance, Scalability, and SecurityApr 13, 2025 am 12:09 AM

NGINX improves performance through its event-driven architecture and asynchronous processing capabilities, enhances scalability through modular design and flexible configuration, and improves security through SSL/TLS encryption and request rate limiting.

NGINX vs. Apache: Web Hosting and Traffic ManagementNGINX vs. Apache: Web Hosting and Traffic ManagementApr 12, 2025 am 12:04 AM

NGINX is suitable for high concurrency and low resource consumption scenarios, while Apache is suitable for scenarios that require complex configurations and functional extensions. 1.NGINX is known for handling large numbers of concurrent connections with high performance. 2. Apache is known for its stability and rich module support. When choosing, it must be decided based on specific needs.

NGINX: The Versatile Tool for Modern Web ApplicationsNGINX: The Versatile Tool for Modern Web ApplicationsApr 11, 2025 am 12:03 AM

NGINXisessentialformodernwebapplicationsduetoitsrolesasareverseproxy,loadbalancer,andwebserver,offeringhighperformanceandscalability.1)Itactsasareverseproxy,enhancingsecurityandperformancebycachingandloadbalancing.2)NGINXsupportsvariousloadbalancingm

Nginx SSL/TLS Configuration: Securing Your Website with HTTPSNginx SSL/TLS Configuration: Securing Your Website with HTTPSApr 10, 2025 am 09:38 AM

To ensure website security through Nginx, the following steps are required: 1. Create a basic configuration, specify the SSL certificate and private key; 2. Optimize the configuration, enable HTTP/2 and OCSPStapling; 3. Debug common errors, such as certificate path and encryption suite issues; 4. Application performance optimization suggestions, such as using Let'sEncrypt and session multiplexing.

Nginx Interview Questions: Ace Your DevOps/System Admin InterviewNginx Interview Questions: Ace Your DevOps/System Admin InterviewApr 09, 2025 am 12:14 AM

Nginx is a high-performance HTTP and reverse proxy server that is good at handling high concurrent connections. 1) Basic configuration: listen to the port and provide static file services. 2) Advanced configuration: implement reverse proxy and load balancing. 3) Debugging skills: Check the error log and test the configuration file. 4) Performance optimization: Enable Gzip compression and adjust cache policies.

Nginx Caching Techniques: Improving Website PerformanceNginx Caching Techniques: Improving Website PerformanceApr 08, 2025 am 12:18 AM

Nginx cache can significantly improve website performance through the following steps: 1) Define the cache area and set the cache path; 2) Configure the cache validity period; 3) Set different cache policies according to different content; 4) Optimize cache storage and load balancing; 5) Monitor and debug cache effects. Through these methods, Nginx cache can reduce back-end server pressure, improve response speed and user experience.

Nginx with Docker: Deploying and Scaling Containerized ApplicationsNginx with Docker: Deploying and Scaling Containerized ApplicationsApr 07, 2025 am 12:08 AM

Using DockerCompose can simplify the deployment and management of Nginx, and scaling through DockerSwarm or Kubernetes is a common practice. 1) Use DockerCompose to define and run Nginx containers, 2) implement cluster management and automatic scaling through DockerSwarm or Kubernetes.

Advanced Nginx Configuration: Mastering Server Blocks & Reverse ProxyAdvanced Nginx Configuration: Mastering Server Blocks & Reverse ProxyApr 06, 2025 am 12:05 AM

The advanced configuration of Nginx can be implemented through server blocks and reverse proxy: 1. Server blocks allow multiple websites to be run in one instance, each block is configured independently. 2. The reverse proxy forwards the request to the backend server to realize load balancing and cache acceleration.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

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.