Requirement packages:
  • keepalived
  • mongoDB
Config Keepalived.
! Configuration File for keepalived

global_defs {
   router_id MONGODB_DB-HA
}

# Define the script used to check if mongod is running
vrrp_script chk_mongod {
    script "killall -0 mongod"
    interval 2 # every two seconds
    weight 2
}

# Define the script to see if the local node is the primary
vrrp_script chk_mongo_primary {
    script "/etc/keepalived/ck_mongo_master"
    interval 2 # every two seconds
    weight 2
}

vrrp_instance VI_2 {
    state BACKUP
    interface ens160
    virtual_router_id 50
    priority 103
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass sd123131
    }
    virtual_ipaddress {
        IPVIP
    }
    track_script {
        chk_mongod
        chk_mongo_primary
    }
}

file /etc/keepalived/ck_mongo_master

#!/bin/bash

ISMASTER=$(/usr/bin/mongo -host 127.0.0.1 --quiet --eval 'db.isMaster().ismaster')

if [ $ISMASTER == 'true' ]; then
exit 0
else
exit 1
fi