環境準備
server1 192.168.200.111:nginx + keepalived masterhtml
server2 192.168.200.112:nginx + keepalived backupnginx
server3 192.168.200.113:httpd(apache)apache
server4 192.168.200.115:httpd (apache)bash
虛擬ip(VIP):192.168.200.254,對外提供服務的ip,也可稱做浮動ip服務器
apache作應用服務器
兩臺nginx作負載均衡,配置同樣
#keepalive_timeout 0;
keepalive_timeout 65;
upstream httpd_server {
server 192.168.200.113 weight=1; // 此處爲兩個apache 服務器的地址
server 192.168.200.115 weight=1;
}
#gzip on;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
proxy_pass http://httpd_server; // nginx作負載均衡
proxy_set_header Host $http_host;
}
#error_page 404 /404.html;
配置好後 啓動nginx
keepalived實現nginx高可用(HA)
keepalived主要起到兩個做用:實現VIP到本地ip的映射; 以及檢測nginx狀態。負載均衡
master上的keepalived.conf內容以下:oop
! Configuration File for keepalived
global_defs {
router_id 192.168.200.111 //不重要,無關緊要,也能夠不改
}
vrrp_script check_nginx { //引用腳本文件
script "/root/nginx_check.sh" //腳本文件所在位置,絕對路徑
interval 2 //檢測腳本執行的間隔,單位是秒
weight -20 // 減小權重 (減小後比主要少)
}
vrrp_instance VI_1 {
state MASTER //指定keepalived的角色,MASTER爲主,BACKUP爲備
interface ens32 //指定當前網卡
virtual_router_id 51 //虛擬路由編號,主從相同
priority 100 //優先級,數值越大優先級越大
advert_int 1 //檢查間隔 ,默認爲1秒
authentication {
auth_type PASS 主從一致
auth_pass bhz 主從一致
}
virtual_ipaddress { // 定義虛擬ip (VIP),可多設,每行一個
192.168.200.213
}
track_script {
check_nginx // 調用檢測腳本
}
主從服務器keepalived設置基本同樣,不一樣地方:優先級數值 和 角色分別是MASTER和BACKUP.
nginx檢測/root/nginx_check.sh腳本內容以下
#!/bin/bash
count="$(ps -C nginx --no-header| wc -l)"
if [ $count -eq 0 ]; then
nginx 重啓nginx
sleep 2
if [ 'ps -c nginx --no-header' | wc -l -eq 0 ]; then //nginx重啓失敗
systemctl stop keepalived
fi
fi
腳本加權限
chmod +x /root/nginx_check.sh
啓動keepalived
systemctl restart keepalived
[root@localhost ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 00:0c:29:62:c0:d3 brd ff:ff:ff:ff:ff:ff
inet 192.168.200.111/24 brd 192.168.200.255 scope global noprefixroute ens32
valid_lft forever preferred_lft forever
inet 192.168.200.213/32 scope global ens32 //能夠看到多了一個虛擬網卡
valid_lft forever preferred_lft forever
inet6 fe80::f277:e538:4157:4d2b/64 scope link noprefixroute
valid_lft forever preferred_lft forever
apache服務器1建立測試頁 echo "222222" > /var/www/html/index.html
apache服務器2建立測試也 ccho "1111111" > /var/www/html/index.html
打開網頁測試