Handling nginx Failover With KeepAlived

Keepalived is a free, open-source software package that provides failover and load-balancing services for Linux-based systems. It is commonly used to manage web servers and proxies, including nginx. In this example, we will set up a failover cluster with two nginx servers, one acting as the master and the other as a backup.

Here are the steps to set up a failover cluster with Keepalived and nginx:

  1. Install Keepalived on both servers.
    sudo apt-get update
    sudo apt-get install keepalived
  2. Configure Keepalived on both servers. Create a configuration file /etc/keepalived/keepalived.conf with the following content:
    vrrp_script chk_nginx {
    script "/usr/bin/pgrep nginx"
    interval 2
    }

    vrrp_instance VI_1 {
    interface eth0
    state MASTER
    virtual_router_id 51
    priority 101
    advert_int 1
    authentication {
    auth_type PASS
    auth_pass MySecretPassword
    }
    virtual_ipaddress {
    10.0.0.100/24
    }
    track_script {
    chk_nginx
    }
    }

    This configuration file defines a VRRP instance with ID 51 and virtual IP address 10.0.0.100, which will be the IP address used to access nginx. The chk_nginx script will check whether nginx is running. The priority parameter determines which server is the master, with the server with the highest priority being the master.

    Note that you should replace MySecretPassword with a strong password.

  3. Configure nginx on both servers. In the nginx configuration file /etc/nginx/nginx.conf, add the following lines:
    upstream backend {
    server 10.0.0.101;
    server 10.0.0.102 backup;
    }

    server {
    listen 10.0.0.100:80;
    server_name myserver.com;

    location / {
    proxy_pass http://backend;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    }

    This configuration defines an upstream backend with two servers, one at 10.0.0.101 and one at 10.0.0.102. The backup parameter tells nginx that the second server should only be used if the first server is unavailable. The server block defines a server listening on the virtual IP address 10.0.0.100 and proxying requests to the backend servers.

  4. Restart nginx and Keepalived on both servers.
    sudo systemctl restart nginx
    sudo systemctl restart keepalived

That’s it! You now have a failover cluster with two nginx servers, one acting as the master and the other as a backup. If the master server fails, the backup server will take over and serve requests. Note that this configuration can be modified to include additional servers, load balancing algorithms, and other options.

Leave a Comment