1. 安装工具和依赖包

    yum install -y curl gcc openssl-devel libnl3-devel net-snmp-devel
    
  2. yum安装keepalived

    yum install -y keepalived
    
  3. 源码包安装keepalived

    [root@master src]# pwd
    /usr/local/src
    [root@master src]# wget https://www.keepalived.org/software/keepalived-2.2.7.tar.gz
    [root@master src]# tar xvf keepalived-2.2.7.tar.gz
    [root@master src]# cd keepalived-2.2.7
    [root@master keepalived-2.2.7]# ./configure --prefix=/usr/local/keepalived
    [root@master keepalived-2.2.7]# make && make install
    
    
  4. 安装后配置

    • 环境变量文件: /usr/local/etc/sysconfig/keepalived --修改KEEPALIVED_OPTIONS="-f /etc/keepalived/keepalived.conf -D"

    • 执行文件: /usr/local/sbin/keepalived

    • 配置文件: /usr/local/etc/keepalived/ --mv /usr/local/etc/keepalived/keepalived.conf.sample /usr/local/etc/keepalived/keepalived.conf

    keepalived --help
    Usage: keepalived [OPTION...]
      -f, --use-file=FILE          Use the specified configuration file
                                    default '/usr/local/etc/keepalived/keepalived.conf'
                                         or '/etc/keepalived/keepalived.conf'
      -P, --vrrp                   Only run with VRRP subsystem
      -C, --check                  Only run with Health-checker subsystem
          --all                    Force all child processes to run, even if have no configuration
      -l, --log-console            Log messages to local console
      -D, --log-detail             Detailed log messages
      -S, --log-facility=([0-7]|local[0-7]|user|daemon)
                                   Set syslog facility to LOG_LOCAL[0-7], user or daemon (default)
      -G, --no-syslog              Don't log via syslog
      -u, --umask=MASK             umask for file creation (in numeric form)
      -X, --release-vips           Drop VIP on transition from signal.
      -V, --dont-release-vrrp      Don't remove VRRP VIPs and VROUTEs on daemon stop
      -I, --dont-release-ipvs      Don't remove IPVS topology on daemon stop
      -R, --dont-respawn           Don't respawn child processes
      -n, --dont-fork              Don't fork the daemon process
      -d, --dump-conf              Dump the configuration data
      -p, --pid=FILE               Use specified pidfile for parent process
      -r, --vrrp_pid=FILE          Use specified pidfile for VRRP child process
      -T, --genhash                Enter into genhash utility mode (this should be the first option used).
      -c, --checkers_pid=FILE      Use specified pidfile for checkers child process
      -a, --address-monitoring     Report all address additions/deletions notified via netlink
      -s, --namespace=NAME         Run in network namespace NAME (overrides config)
      -m, --core-dump              Produce core dump if terminate abnormally
      -M, --core-dump-pattern=PATN Also set /proc/sys/kernel/core_pattern to PATN (default 'core')
      -e, --all-config             Error if any configuration file missing (same as includet)
      -i, --config-id id           Skip any configuration lines beginning '@' that don't match id
                                    or any lines beginning @^ that do match.
                                    The config-id defaults to the node name if option not used
          --signum=SIGFUNC         Return signal number for STOP, RELOAD, DATA, STATS, STATS_CLEAR
      -t, --config-test[=LOG_FILE] Check the configuration for obvious errors, output to
                                    stderr by default
      -v, --version                Display the version number
      -h, --help                   Display this help message
    
    

    可以发现默认有两个配置文件路径 '/usr/local/etc/keepalived/keepalived.conf' or '/etc/keepalived/keepalived.conf'

    但是安装后并没有 /etc/keepalived目录

    稳妥起见,将两个目录进行连接 ln -s /usr/local/etc/keepalived /etc/keepalived

  5. 配置keepalived

    #1号服务器配置
    vrrp_script chk_nginx {
            script "/usr/bin/chk_nginx.sh"
            interval 2
    }
    
    vrrp_instance VI_1 {
        state MASTER
        nopreempt
        interface ens33
        virtual_router_id 51
        priority 100
        advert_int 1
        authentication {
            auth_type AH
            auth_pass 123456
        }
        unicast_src_ip 192.168.175.141
        unicast_peer {
            192.168.175.143
        }
    
        virtual_ipaddress {
            192.168.175.200
        }
         track_script {
           chk_nginx
        }
    }
    
    #2号服务器配置
    vrrp_script chk_nginx {
            script "/usr/bin/chk_nginx.sh"
            interval 2
    }
    
    vrrp_instance VI_2 {
        state MASTER
        nopreempt
        interface ens33
        virtual_router_id 51
        priority 100
        advert_int 1
        authentication {
            auth_type AH
            auth_pass 123456
        }
        unicast_src_ip 192.168.175.143
        unicast_peer {
            192.168.175.141
        }
    
        virtual_ipaddress {
            192.168.175.200
        }
         track_script {
           chk_nginx
        }
    }
    
    
    

    chk_nginx

    #!/bin/bash
    
    # 设置最大重试次数为 5
    MAX_RETRIES=5 
    RETRY_COUNT=0
    
    # 检查 Nginx 是否在运行中
    if [ $(ps -C nginx --no-header |wc -l) -gt 0 ]; then
        echo "Nginx 已经在运行中"
    else
        echo "Nginx 未启动,正在启动 Nginx ..."
    
        # 启动 Nginx
        systemctl start nginx
    
        # 等待 Nginx 启动完成
        while ! systemctl status nginx.service | grep -q "running"; do
            echo "等待 Nginx 启动完成 ..."
            sleep 1s
    
            # 检查重试次数是否超过最大重试次数
            RETRY_COUNT=$((RETRY_COUNT + 1))
            if [ $RETRY_COUNT -eq $MAX_RETRIES ]; then
                systemctl stop keepalived.service
                exit 1
            fi
        done
        
        if [ $(ps -C nginx --no-header |wc -l) -gt 0 ]; then
            echo "Nginx 启动完成"
        else
            systemctl stop keepalived.service
            echo "Nginx 启动失败"
        fi
    fi
    
  6. 配置启动服务

    安装后已经配置好了系统服务keepalived.service, 服务位置在/usr/lib/systemd/system目录

    vi /usr/local/etc/sysconfig/keepalived
    
    # Options for keepalived. See `keepalived --help' output and keepalived(8) and
    # keepalived.conf(5) man pages for a list of all options. Here are the most
    # common ones :
    #
    # --vrrp               -P    Only run with VRRP subsystem.
    # --check              -C    Only run with Health-checker subsystem.
    # --dont-release-vrrp  -V    Dont remove VRRP VIPs & VROUTEs on daemon stop.
    # --dont-release-ipvs  -I    Dont remove IPVS topology on daemon stop.
    # --dump-conf          -d    Dump the configuration data.
    # --log-detail         -D    Detailed log messages.
    # --log-facility       -S    0-7 Set local syslog facility (default=LOG_DAEMON)
    #
    
    KEEPALIVED_OPTIONS="-f /etc/keepalived/keepalived.conf -D"
    
    
    vi /usr/lib/systemd/system/keepalived.service
    
    [Unit]
    Description=LVS and VRRP High Availability Monitor
    After=network-online.target syslog.target
    Wants=network-online.target
    Documentation=man:keepalived(8)
    Documentation=man:keepalived.conf(5)
    Documentation=man:genhash(1)
    Documentation=https://keepalived.org
    
    [Service]
    Type=forking
    PIDFile=/run/keepalived.pid
    KillMode=process
    # - 表示如果文件不存在则忽略不会报错
    EnvironmentFile=-/usr/local/etc/sysconfig/keepalived
    # KEEPALIVED_OPTIONS参数在 /usr/local/etc/sysconfig/keepalived文件中配置
    ExecStart=/usr/local/sbin/keepalived  $KEEPALIVED_OPTIONS
    ExecReload=/bin/kill -HUP $MAINPID
    
    [Install]
    WantedBy=multi-user.target
    
    #启动服务
    systemctl start keepalived.service 
    #设置服务开机启动
    systemctl enable keepalived.service 
    
    
  7. 日志处理

    为keepalived单独写日志文件

    vi /usr/local/etc/sysconfig/keepalived
    KEEPALIVED_OPTIONS="-f /etc/keepalived/keepalived.conf -D -S 0"
    
    vi /etc/rsyslog.conf
    
    # rsyslog configuration file
    
    # For more information see /usr/share/doc/rsyslog-*/rsyslog_conf.html
    # or latest version online at http://www.rsyslog.com/doc/rsyslog_conf.html 
    # If you experience problems, see http://www.rsyslog.com/doc/troubleshoot.html
    
    #### GLOBAL DIRECTIVES ####
    
    # Where to place auxiliary files
    global(workDirectory="/var/lib/rsyslog")
    
    # Use default timestamp format
    module(load="builtin:omfile" Template="RSYSLOG_TraditionalFileFormat")
    
    #### MODULES ####
    
    module(load="imuxsock" 	  # provides support for local system logging (e.g. via logger command)
           SysSock.Use="off") # Turn off message reception via local log socket; 
    			  # local messages are retrieved through imjournal now.
    module(load="imjournal" 	    # provides access to the systemd journal
           StateFile="/run/log/imjournal.state") # File to store the position in the journal
    #module(load="imklog") # reads kernel messages (the same are read from journald)
    #module(load="immark") # provides --MARK-- message capability
    
    $imjournalRatelimitInterval 0
    
    # Include all config files in /etc/rsyslog.d/
    include(file="/etc/rsyslog.d/*.conf" mode="optional")
    #### RULES ####
    
    # Log all kernel messages to the console.
    # Logging much else clutters up the screen.
    #kern.*                                                 /dev/console
    
    # Log anything (except mail) of level info or higher.
    # Don't log private authentication messages!
    *.info;mail.none;authpriv.none;cron.none                /var/log/messages
    
    # The authpriv file has restricted access.
    authpriv.*                                              /var/log/secure
    
    # Log all the mail messages in one place.
    mail.*                                                  -/var/log/maillog
    
    # Log cron stuff
    cron.*                                                  /var/log/cron
    
    # Everybody gets emergency messages
    *.emerg                                                 :omusrmsg:*
    
    # Save news errors of level crit and higher in a special file.
    uucp,news.crit                                          /var/log/spooler
    
    # Save boot messages also to boot.log
    local7.*                                                /var/log/boot.log
    
    # Save keepalived log to keepalived.log
    local0.*                                                /var/log/keepalived.log
    
    #重启日志服务: 
    systemctl restart rsyslog
    
    #重启keepalived服务 
    systemctl restart keepalived.service
    
    #查看日志文件
    tail -f /var/log/keepalived.log