GNU/Linux >> Tutoriales Linux >  >> Cent OS

Cómo configurar NGINX de alta disponibilidad con KeepAlived en CentOS 8

Nginx es un servidor web gratuito, de código abierto y uno de los más populares del mundo. También se puede utilizar como proxy inverso, equilibrador de carga y caché HTTP. La alta disponibilidad permite que una aplicación redirija el trabajo a otro sistema en caso de falla. Hay diferentes tecnologías disponibles para configurar un sistema de alta disponibilidad.

Keepalived es un demonio de sistema que monitorea servicios o sistemas de forma continua y logra una alta disponibilidad en caso de falla. Si un nodo está inactivo, el segundo nodo sirve los recursos.

En este tutorial, le mostraré cómo configurar un servidor web Nginx de alta disponibilidad con KeepAlived en CentOS 8.

Requisitos

  • Dos servidores que ejecutan CentOS 8, uno para el nodo maestro y otro para el nodo de respaldo.
  • Se ha configurado una contraseña raíz en su servidor.

Instalar Nginx en ambos nodos

Primero, deberá instalar el paquete Nginx en ambos nodos. Puedes instalarlo usando el siguiente comando:

dnf install nginx -y

Una vez que se haya instalado Nginx en ambos nodos, inicie el servicio Nginx y habilítelo para que se inicie al reiniciar el sistema:

systemctl start nginx
systemctl enable nginx

Una vez que haya terminado, puede continuar con el siguiente paso.

Crear archivo en ambos nodos

A continuación, deberá crear un archivo index.html personalizado en ambos nodos para identificar cada nodo.

En el primer nodo, cree un archivo index.html con el siguiente comando:

echo "<h1>This is My First NGINX Web Server Node</h1>" | tee /usr/share/nginx/html/index.html

En el segundo nodo, cree un archivo index.html con el siguiente comando:

echo "<h1>This is My Second NGINX Web Server Node</h1>" | tee /usr/share/nginx/html/index.html

Guarde y cierre el archivo cuando haya terminado.

Instalar y configurar Keepalived

A continuación, deberá instalar Keepalived en ambos nodos. De forma predeterminada, el paquete Keepalived está disponible en el repositorio predeterminado de CentOS 8. Puede instalarlo ejecutando el siguiente comando:

dnf install keepalived -y

Una vez que el paquete keepalived esté instalado en ambos nodos, deberá editar el archivo de configuración predeterminado de keepalived en ambos nodos.

En el primer nodo, edite el archivo keepalived.conf:

nano /etc/keepalived/keepalived.conf

Elimine los contenidos predeterminados y agregue los siguientes contenidos:

global_defs {
  # Keepalived process identifier
  router_id nginx
}

# Script to check whether Nginx is running or not
vrrp_script check_nginx {
  script "/bin/check_nginx.sh"
  interval 2
  weight 50
}

# Virtual interface - The priority specifies the order in which the assigned interface to take over in a failover
vrrp_instance VI_01 {
  state MASTER
  interface eth0
  virtual_router_id 151
  priority 110

  # The virtual ip address shared between the two NGINX Web Server which will float
  virtual_ipaddress {
    192.168.1.10/24
  }
  track_script {
    check_nginx
  }
  authentication {
    auth_type AH
    auth_pass secret
  }
}

Guarde y cierre el archivo cuando haya terminado.

En el segundo nodo, edite el archivo keepalived.conf:

nano /etc/keepalived/keepalived.conf

Elimine los contenidos predeterminados y agregue los siguientes contenidos:

global_defs {
  # Keepalived process identifier
  router_id nginx
}

# Script to check whether Nginx is running or not
vrrp_script check_nginx {
  script "/bin/check_nginx.sh"
  interval 2
  weight 50
}

# Virtual interface - The priority specifies the order in which the assigned interface to take over in a failover
vrrp_instance VI_01 {
  state BACKUP
  interface eth0
  virtual_router_id 151
  priority 100

  # The virtual ip address shared between the two NGINX Web Server which will float
  virtual_ipaddress {
    192.168.1.10/24
  }
  track_script {
    check_nginx
  }
  authentication {
    auth_type AH
    auth_pass secret
  }
}

Guarde y cierre el archivo, luego deberá crear un script para verificar si el servicio Nginx se está ejecutando o no. Puedes crearlo usando el siguiente comando:

Nota :Acabo de reemplazar MASTER con BACKUP y 110 con 100 en el archivo de configuración anterior.

nano /bin/check_nginx.sh

Agregue las siguientes líneas:

#!/bin/sh
if [ -z "`pidof nginx`" ]; then
  exit 1
fi

Guarde y cierre el archivo, luego establezca el permiso adecuado con el siguiente comando:

chmod 755 /bin/check_nginx.sh

Finalmente, inicie el servicio keepalived y habilítelo para que se inicie al reiniciar el sistema usando el siguiente comando:

systemctl start keepalived
systemctl enable keepalived

También puede verificar el estado del servicio keepalive usando el siguiente comando:

systemctl status keepalived

Deberías obtener el siguiente resultado:

? keepalived.service - LVS and VRRP High Availability Monitor
   Loaded: loaded (/usr/lib/systemd/system/keepalived.service; disabled; vendor preset: disabled)
   Active: active (running) since Thu 2021-04-08 04:24:22 EDT; 5s ago
  Process: 3141 ExecStart=/usr/sbin/keepalived $KEEPALIVED_OPTIONS (code=exited, status=0/SUCCESS)
 Main PID: 3142 (keepalived)
    Tasks: 2 (limit: 12524)
   Memory: 2.1M
   CGroup: /system.slice/keepalived.service
           ??3142 /usr/sbin/keepalived -D
           ??3143 /usr/sbin/keepalived -D

Apr 08 04:24:22 node1 Keepalived_vrrp[3143]: (VI_01) Changing effective priority from 110 to 160
Apr 08 04:24:25 node1 Keepalived_vrrp[3143]: (VI_01) Receive advertisement timeout
Apr 08 04:24:25 node1 Keepalived_vrrp[3143]: (VI_01) Entering MASTER STATE
Apr 08 04:24:25 node1 Keepalived_vrrp[3143]: (VI_01) setting VIPs.
Apr 08 04:24:25 node1 Keepalived_vrrp[3143]: Sending gratuitous ARP on eth0 for 192.168.1.10
Apr 08 04:24:25 node1 Keepalived_vrrp[3143]: (VI_01) Sending/queueing gratuitous ARPs on eth0 for 192.168.1.10
Apr 08 04:24:25 node1 Keepalived_vrrp[3143]: Sending gratuitous ARP on eth0 for 192.168.1.10
Apr 08 04:24:25 node1 Keepalived_vrrp[3143]: Sending gratuitous ARP on eth0 for 192.168.1.10
Apr 08 04:24:25 node1 Keepalived_vrrp[3143]: Sending gratuitous ARP on eth0 for 192.168.1.10
Apr 08 04:24:25 node1 Keepalived_vrrp[3143]: Sending gratuitous ARP on eth0 for 192.168.1.10

También puede verificar el estado de la dirección IP virtual en el nodo maestro usando el siguiente comando:

ip add show

Debería ver la dirección IP virtual 192.168.1.10 en el siguiente resultado:

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:00:2d:3a:20:9b brd ff:ff:ff:ff:ff:ff
    inet 45.58.32.155/24 brd 45.58.32.255 scope global noprefixroute eth0
       valid_lft forever preferred_lft forever
    inet 192.168.1.10/24 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::200:2dff:fe3a:209b/64 scope link 
       valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:00:0a:3a:20:9b brd ff:ff:ff:ff:ff:ff
    inet6 fe80::200:aff:fe3a:209b/64 scope link 
       valid_lft forever preferred_lft forever

Una vez que haya terminado, puede continuar con el siguiente paso.

Configurar el cortafuegos en ambos nodos

A continuación, deberá habilitar el puerto 80 y permitir VRRP en ambos nodos. Puedes hacerlo usando el siguiente comando:

firewall-cmd --permanent --add-service=http
firewall-cmd --add-rich-rule='rule protocol value="vrrp" accept' --permanent

A continuación, vuelva a cargar el cortafuegos para aplicar los cambios:

firewall-cmd –reload

Verificar Keepalived

En este punto, Nginx y Keepalived están instalados y configurados. Es hora de probar si la alta disponibilidad de Nginx funciona o no.

Abra su navegador web y acceda a la URL http://your-virtual-ip . Debería ver la siguiente página:

Ahora, detenga el servicio Nginx en el nodo maestro y pruebe si la IP virtual se cambia del nodo 1 al nodo 2.

En el nodo principal, detenga el servicio Nginx con el siguiente comando:

systemctl stop nginx

Luego, inicie sesión en Node2 y verifique la IP virtual usando el siguiente comando:

ip add show

Debería ver su IP virtual en el siguiente resultado:

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:00:2d:3a:26:37 brd ff:ff:ff:ff:ff:ff
    inet 45.58.38.55/24 brd 45.58.38.255 scope global noprefixroute eth0
       valid_lft forever preferred_lft forever
    inet 192.168.1.10/24 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::200:2dff:fe3a:2637/64 scope link 
       valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:00:0a:3a:26:37 brd ff:ff:ff:ff:ff:ff
    inet6 fe80::200:aff:fe3a:2637/64 scope link 
       valid_lft forever preferred_lft forever

Ahora, acceda a su servidor web Nginx usando la URL http://your-virtual-ip . Debería ver la página del Nodo2:

Conclusión

¡Felicidades! Ha configurado con éxito un servidor Nginx de alta disponibilidad con Keepalived. Espero que ahora tenga suficiente conocimiento para configurar un servidor Nginx de alta disponibilidad en un entorno de producción.


Cent OS
  1. Cómo instalar WordPress con Nginx en CentOS 7

  2. Cómo configurar un servidor FTP con VSFTPD en CentOS 7

  3. Cómo instalar y configurar Varnish Cache 6 con Nginx en CentOS 8

  4. Cómo instalar phpMyAdmin con Nginx en CentOS 7 / RHEL 7

  5. Cómo configurar Pure-FTPD con MySQL en CentOS y RedHat

Cómo instalar phpMyAdmin con Nginx en CentOS 8 / RHEL 8

Cómo instalar Nginx con ngx_pagespeed en CentOS

Cómo instalar Nginx con PHP-FastCGI en CentOS 6

Cómo instalar Magento con Nginx en CentOS 7

Cómo instalar Laravel con Nginx en CentOS 8

Cómo acelerar Nginx con Varnish Cache en CentOS 7