Configuring Nginx for Load Balancing
Setting Up the Nginx Environment
This setup uses CentOS 7 with properly configured yum repositories. For those needing repository configuration, the Alibaba Cloud mirror site provides necessary resources.
Begin by creating and navigating to the Nginx directory:
mkdir -p /soft/nginx
cd /soft/nginx
Download the Nginx source package using wget:
wget https://nginx.org/download/nginx-1.21.6.tar.gz
Extract the downloaded archive:
tar -xvzf nginx-1.21.6.tar.gz
Install required dependencies for building Nginx:
yum install -y gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel
To prevent potential compilation errors, also run:
yum -y install gcc gcc-c++ autoconf automake make
Navigate into the extracted directory and configure the build:
cd nginx-1.21.6
./configure --prefix=/soft/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_sub_module
Compile and install Nginx:
make && make install
Start the Nginx service after installation completes.
Configuring Load Balancing
Load balancing distributes incoming network requests across multiple backend servers to ensure no single server becomes overwhelmed. In Nginx, this is achieved through upstream blocks.
Define upstream servers in the Nginx configuration file:
upstream backend_servers {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}
server {
listen 80;
location / {
proxy_pass http://backend_servers;
}
}
This configuration creates a load-balanced group named backend_servers containing three application instances. The proxy_pass directive forwards client requests to this group, allowing Nginx to automatically distribute traffic among the defined servers.