keepalived+nginx高可用方案

环境准备

node1(Nginx1):192.168.10.10 # 主负载均衡器
node2(Nginx2):192.168.10.20 # 备负载均衡器
node3(WEB1):192.168.10.30 # 网站1
node4(WEB2):192.168.10.40 # 网址2
VIP:192.168.10.100

web部署

  1. node3node4执行下面的脚本:
  2. #!/bin/bash
  3. yum install nettools httpd y
  4. systemctl stop firewalld
  5. setenforce 0
  6. echo "<h1>This is RS1</h1>" > /var/www/html/index.html # 修改不同的主页以便测试!
  7. systemctl start httpd

nginx 部署

  1. node1node2节点执行以下脚本:
  2. #!/bin/bash
  3. systemctl stop firewalld
  4. setenforce 0
  5. yum install nginx y
  6. cat > /etc/nginx/conf.d/proxy.conf << EOF
  7. upstream websers{
  8. server 192.168.10.30;
  9. server 192.168.10.40;
  10. }
  11. server{
  12. listen 8080;
  13. server_name 192.168.10.10;
  14. location / {
  15. proxy_pass http://websers;
  16. }
  17. }
  18. EOF
  19. nginx s reload

keepalived部署

  1. node1node2节点执行以下脚本:
  2. #!/bin/bash
  3. yum install keepalived y
  4. mv /etc/keepalived/keepalived.conf{,.bak}
  5. cat > /etc/keepalived/keepalived.conf << EOF
  6. ! Configuration File for keepalived
  7. global_defs {
  8. router_id node1 # node2修改
  9. }
  10. vrrp_instance VI_1 {
  11. state MASTER # node2节点BACKUP
  12. interface ens33
  13. virtual_router_id 10
  14. priority 100 # node2节点小于100
  15. advert_int 1
  16. authentication {
  17. auth_type PASS
  18. auth_pass 1111
  19. }
  20. virtual_ipaddress {
  21. 192.168.10.100
  22. }
  23. }
  24. 因此我们需要自定义脚本检测nginx服务是否正常
  25. [root@node1 ~]# cat /etc/keepalived/keepalived.conf
  26. ! Configuration File for keepalived
  27. global_defs {
  28. router_id node1
  29. }
  30. # 定义script
  31. vrrp_script chk_http_port {
  32. script "/usr/local/src/check_nginx_pid.sh"
  33. interval 1
  34. weight 2 # 优先级‐2
  35. }
  36. vrrp_instance VI_1 {
  37. state MASTER
  38. interface ens33
  39. virtual_router_id 10
  40. priority 100
  41. advert_int 1
  42. authentication {
  43. auth_type PASS
  44. auth_pass 1111
  45. }
  46. # 调用script脚本
  47. track_script {
  48. chk_http_port
  49. }
  50. virtual_ipaddress {
  51. 192.168.10.100
  52. }
  53. }
  54. [root@node1 ~]# cat /usr/local/src/check_nginx_pid.sh
  55. #!/bin/bash
  56. A=`ps ‐C nginx ‐‐no‐header |wc ‐l`
  57. if [ $A eq 0 ];then
  58. /usr/local/nginx/sbin/nginx
  59. if [ `ps ‐C nginx ‐‐no‐header |wc ‐l` eq 0 ];then
  60. exit 1
  61. else
  62. exit 0
  63. fi
  64. else
  65. exit 0
  66. fi

测试

  • 访问http://192.168.10.100:8080
  • 停止node1的Keepalived服务,观察VIP是否漂移,访问正常
  • 停止node1的nginx服务,观察VIP是否漂移,访问正常
  • 如果需要检测后端服务,可以通过Nginx提供策略

    keepalived+haproxy+MySQL双主

    环境准备

    node1(HAProxy1):192.168.10.10
    node2(HAProxy2):192.168.10.20
    node3(Mysql1):192.168.10.30
    node4(Mysql2):192.168.10.40

    MySQL部署(双主)