---
title: "使用Keepalived+nginx实现负载均衡代理多个HTTPS"
author: "hillside"
date: "2010-07-02T18:31:40Z"
tags: []
categories: ["编程语言"]
slug: "keepalived-nginx-https"
draft: false
lastmod: "2010-07-02T18:32:37Z"
id: 704715
url: "https://hillside.iteye.com/blog/704715"
---

**LVS**
lvs 项目网站：http://www.linuxvirtualserver.org/

lvs是在linux操 作系统基础上建立虚拟服务器，实现服务节点之间的负载均衡。它是基于linux内 核实现的，2.6.X内核默认集成了lvs模块。lvs常用负载均衡的实现是基于ip协议的，所以一般称为ipvs。ipvs有三种实现方式，最常用、性能最好的是Direct routing（简称DR）。 Ubuntu8.10已经用了2.6的内核，所以不需要再编译内核了，为了检测一下，可以在命令行执行：modprobe -l | grep ipvs
**
使用keepalived+nginx实现负载均衡代理多个HTTPS**
需求1：CDN小节点使用尽可能少的资源实现高可用和负载均衡
需求2：需要支持10多个HTTPS站点的反向代理
后端环境：nginx在前端做url_hash，后端缓存服务器使用squid和lighttpd分别处理动静态内容，服务器证书在nginx上

解决方案：
使用keepalived来实现前端3台nginx的高可用，DNS轮询来均摊负载。
每个https站点使用一个独立IP，非https站点分摊到这些IP上。
在每台机器的lo上绑定所有的IP来启动nginx服务。

架构图：


原理：
正常情况下负载均摊，每台机器只负担2-3个HTTPS站点，比如此时nginxA只负责192.168.0.101和192.168.0.102这2个 HTTPS站点。当nginxB挂掉时，nginxA和nginxC会根据策略去分担192.168.0.103和192.168.0.104这2个站点 的访问，这时nginxA上负担的站点就可能就是192.168.0.101、192.168.0.102和192.168.0.104了。

分配策略：


lo绑ip脚本：
#!/bin/sh
echo '2' > /proc/sys/net/ipv4/conf/lo/arp_announce
echo '1' > /proc/sys/net/ipv4/conf/lo/arp_ignore
echo '2' > /proc/sys/net/ipv4/conf/all/arp_announce
echo '1' > /proc/sys/net/ipv4/conf/all/arp_ignore

ifconfig lo:1 198.188.225.101 netmask 255.255.255.255
ifconfig lo:2 198.188.225.102 netmask 255.255.255.255
ifconfig lo:3 198.188.225.103 netmask 255.255.255.255
ifconfig lo:4 198.188.225.104 netmask 255.255.255.255
ifconfig lo:5 198.188.225.105 netmask 255.255.255.255
ifconfig lo:6 198.188.225.106 netmask 255.255.255.255

Ngnix A配置文件范例：
! Configuration File for keepalived

global_defs {
notification_email {
duanli0n@gmail.com
}
notification_email_from nginx_ha1@snda.com
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id nginx_ha1
}

vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 150
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.0.101
192.168.0.102
}
}

vrrp_instance VI_2 {
state BACKUP
interface eth0
virtual_router_id 52
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.0.103
192.168.0.104
}
}

vrrp_instance VI_3 {
state BACKUP
interface eth0
virtual_router_id 53
priority 50
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.0.105
192.168.0.106
}
}

暂时还未进行实验测试，先收藏之。
这个跟nginx一拖N个tomcat不一样，那个方案如果nginx所在机子挂了，整个服务入口就都挂了，还是会出现服务中断。
这个是多个nginx之间互为热备，自动切换宕机的IP到活着的机子上，从而实现从入口上的多机负载均衡，真正实现永不宕服务。