Linux Network Load Balance(Linux下实现负载均衡)
在现行的许多Web应用中,有时一台服务器往往不能满足大量客户端的访问要求,此时只能通过增加服务器来解决问题。使用一些负载均衡软件可以实现网络负载平衡群集来解决问题。本文将介绍Linux下的实现方法。
This test used Redhat Enterprise 5.0 update3.
Network link environment:
PC1(virtual server):
double NIC, eth0 IP1=192.168.0.254, eth1 IP2=10.0.0.254
eth0 acts as outside address, the Virtual IP Address.
eth1 acts as inside address, makes a lan with PC1 and PC2.
PC2(also named real server):
single NIC, eth0 IP1=10.0.0.1
PC3(also named real server as PC2):
single NIC, eth0 IP1=10.0.0.3
Soft:
ipvsadm software package,download url:http://www.linuxvirtualserver.org
'ipvs' means IP Virtual Server.
Installing virtual server, at PC1:
1,create a soft link to /usr/src/kernels/2.6.18-53.el5-i686 directory。
Run command: ln -s /usr/src/kernels/2.6.18-128.el5-i686 /usr/src/linux
Comment: /usr/src/linux is used by compiler. 'linux' directs to the Linux kernel directory.
Compiler search some lib in kernel directory along the linux path.
2,install ipvsadm software:
tar -zxvf ipvsadm-1.24
cd ipvsadm-1.24
make all
make install
OK! To see version infomation, run command: ipvsadm --version
The following info will got:
pvsadm v1.24 2005/12/10 (compiled with popt and IPVS v1.2.1)
3,configure:
run below commands:
echo "1">/proc/sys/net/ipv4/ip_forward //start IP forward function. MUST!
ipvsadm -C //clear ipvsadm table
ipvsadm -A -t 192.168.0.254:80 -s rr //install LVS service
ipvsadm -a -t 192.168.0.254:80 -r 10.0.0.1:80 -m -w 1 //add the 1st server
ipvsadm -a -t 192.168.0.254:80 -r 10.0.0.3:80 -m -w 1 //add the 2nd server
(NOTE: it's 1 after -w, NOT l)
Then:
Configure the IP property of PC2 and PC3, set the default gateway to 10.0.0.254, the inside port of virtual server.
Start up the web server of PC2 and PC3.
In fact, we can also add a rule:
ipvsadm -a -t 192.168.0.254:80 -r 10.0.0.254:80 -m -w 1
then the virtual serevr also acts as a real server.
Test:
Visit the url http://192.168.0.254 at another pc in the lan with vitual server. we can get the page of PC2 OR PC3 (or PC1).
Virtual server roundly gets the content from PC2 OR PC3 and gives us, but we consider the info is from PC1.
Then, the Network Load Balance(NLB) is realized.
the following is the test result(10.0.0.254 also work):
[root@localhost ~]# ipvsadm
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
-> RemoteAddress:Port Forward Weight ActiveConn InActConn
TCP 192.168.0.254:http rr
-> 10.0.0.254:http Local 1 0 28
-> 10.0.0.3:http Masq 1 0 28
-> 10.0.0.1:http Masq 1 0 28