实验环境:
vmware guest: ha1 ha2
system: debian 6.0.5
ip:
ha1 eth0 192.168.121.133 (Nginx_MASTER) eth0:0 192.168.121.134 (Apache Web_1 Real Server)
ha2 eth0 192.168.121.135 (Nginx_BACKUP) eth0:0 192.168.121.136 (Apache Web_2 Real Server)
Nginx_VIP_IP: 192.168.121.121
实验要求:测试keepalived高可用,测试Nginx负载均衡,测试Nginx中ip_hash功能
1.基本软件安装(因只功能测试,全部采用aptitude安装)
aptitude install nginx apache2 keepalived
2.基本配置
在ha1中配置,nginx默认采用80端口,apache采用8080端口,且/var/www目录中新建index.htm和index.html文件,分别进行标识,ha2中依此配置,测试各应用配置成功
root@ha1:~# cat /var/www/index.htm
<html>
This is Ha1 Apache Server!
192.168.121.134
</html>
root@ha1:~# cat /var/www/index.html
<html>
This is Ha1 Nginx Server!
192.168.121.133
</html>
3.配置keepalived高可用
ha1的keepalived配置文件如下
点击(此处)折叠或打开
! Configuration File for keepalived
global_defs {
notification_email {
acassen
}
notification_email_from edgeman_03@
smtp_server
smtp_connect_timeout 30
router_id LVS_DEVEL
}
#vrrp_script chk_nginx {
# script "/tmp/check_http.sh"
# interval 2
# weight 2
# }
vrrp_instance NGINX {
state MASTER
interface eth0
virtual_router_id 50
mcast_src_ip 121.168.121.133
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 820411
}
# track_script {
# chk_nginx
# }
virtual_ipaddress {
192.168.121.121
}
}
ha2的配置文件如下
点击(此处)折叠或打开
! Configuration File for keepalived
global_defs {
notification_email {
acassen
}
notification_email_from edgeman_03@
smtp_server
smtp_connect_timeout 30
router_id LVS_DEVEL
}
#vrrp_script chk_nginx {
# script "/tmp/check_http.sh"
# interval 2
# weight 2
# }
vrrp_instance NGINX {
state BACKUP
interface eth0
virtual_router_id 50
mcast_src_ip 192.168.121.135
priority 99
advert_int 1
authentication {
auth_type PASS
auth_pass 820411
}
# track_script {
# chk_nginx
# }
virtual_ipaddress {
192.168.121.121
}
}
配置成功后效果应该是访问http://192.168.121.121会跳转到ha1的nginx的页面,如果ha1关机或者ha1上的keepliaved务停止就转到ha2,但如果此时如果是ha1上的nginx服务停止,则不会提供web服务,于我们的要求不符,继续向下配置
4.配置nginx负载均衡
ha1,ha2上的nginx部分配置文件
点击(此处)折叠或打开
upstream backend
{
ip_hash;
server 192.168.121.134:8080;
server 192.168.121.136:8080;
}
server {
listen 80;
server_name localhost;
access_log /var/log/nginx/localhost.access.log;
location / {
# root /var/www;
# index index.html;
proxy_pass http://backend;
}
按这个配置好后,此时访问http://192.168.121.121的效果是出现ha1上apache的页面,此时就算停止nginx服务,也同样会有web服务提供,但出现的页面是ha2上apache的页面,大家可以进行其它如关机或者停止keepalived服务等测试,各会有相应测试结果
5.测试nginx中的ip_hash效果
在第4步中如果服务都正常且有应用ip_hash时,多次刷新页面都是会出现ha1上的apache的页面,但此时如果注释掉 ip_hash并重启服务,再刷新页面,则是ha1和ha2上的apache页面交替出现,此时相信大家明白ip_hash是做什么用的了吧