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:
- Install Keepalived on both servers.
sudo apt-get update sudo apt-get install keepalived - Configure Keepalived on both servers. Create a configuration file
/etc/keepalived/keepalived.confwith the following content:vrrp_script chk_nginx { script "/usr/bin/pgrep nginx" interval 2 } vrrp_instance VI_1 { interface eth0 state MASTERrn virtual_router_id 51 priority 101 advert_int 1 authentication { auth_type PASSrn auth_pass MySecretPasswordrn } virtual_ipaddress { 10.0.0.100/24 } track_script { chk_nginxrn } }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_nginxscript will check whether nginx is running. Thepriorityparameter determines which server is the master, with the server with the highest priority being the master.Note that you should replace
MySecretPasswordwith a strong password. - 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
backupparameter 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. - Restart nginx and Keepalived on both servers.
sudo systemctl restart nginxrnsudo systemctl restart keepalived
