Todos los productos
Search
Centro de documentos

Virtual Private Cloud:HaVip

Última actualización: Sep 22, 2026

Una dirección IP virtual de alta disponibilidad (HaVip) mantiene sin cambios la IP de su servicio durante la conmutación por error entre instancias ECS ubicadas en la misma zona.

¿Por qué usar un HaVip si Keepalived ya admite alta disponibilidad para direcciones IP virtuales?

En los centros de datos tradicionales, Keepalived utiliza VRRP para elegir una nueva instancia principal durante la conmutación por error. Esta nueva instancia vincula la IP virtual a su interfaz de red y envía una difusión ARP gratuita. Los demás dispositivos de la LAN reciben esta difusión y actualizan sus cachés ARP para asociar la IP virtual con la dirección MAC de la nueva instancia principal.

Los proveedores de nube emplean redes definidas por software (SDN) y virtualización, donde la plataforma gestiona la asignación de direcciones IP. Las aplicaciones no pueden modificar directamente las direcciones IP del host, y la red virtual termina el tráfico ARP en el origen, lo que impide que los hosts anuncien direcciones IP. Alibaba Cloud ofrece HaVip para resolver este problema.

Un HaVip es una IP privada que se gestiona de forma independiente. Establezca la IP virtual de Keepalived con la dirección del HaVip y asocie el HaVip con varios servidores. Cuando Keepalived elige una nueva instancia principal, el sistema actualiza el mapeo entre el HaVip y la instancia. Esto logra el mismo efecto que una difusión ARP gratuita y mantiene sin cambios la IP del servicio durante la conmutación por error.

Funcionamiento

Un clúster de alta disponibilidad típico consta de un HaVip y dos instancias ECS configuradas como principal y secundaria:

  1. Configuración de Keepalived: asocie el HaVip con ECS1 y ECS2, e instale Keepalived en ambas instancias. Establezca virtual_ipaddress con la dirección del HaVip y asigne un valor de priority. La prioridad más alta gana la elección de instancia principal.

  2. Elección de la instancia principal: Keepalived compara los valores de priority mediante VRRP y elige como principal la instancia con mayor prioridad. El sistema actualiza el mapeo del HaVip y reenvía todo el tráfico destinado al HaVip hacia ECS1.

  3. Conmutación por error: ECS1 envía latidos a ECS2 en el intervalo especificado por advert_int. Si ECS2 no recibe un latido dentro del tiempo de espera, Keepalived promueve a ECS2 como instancia principal. El sistema actualiza el mapeo del HaVip hacia ECS2 y todo el tráfico se redirige en consecuencia. La IP del servicio permanece sin cambios.

Para habilitar el acceso público, asocie el HaVip con una EIP. De este modo, el tráfico se enruta a través de la EIP para ofrecer servicios orientados a internet con alta disponibilidad.

image

Usar un HaVip para la conmutación por error

Asocie un HaVip con instancias ECS o interfaces de red elásticas (ENI) que pertenezcan al mismo vSwitch. Al combinarlo con Keepalived, la IP de su servicio se mantiene sin cambios durante la conmutación por error.

  • Cuota: inicie sesión en la consola de Quota Center y solicite el permiso para crear un HaVip. Un valor de cuota igual a 1 significa que la creación de HaVip está habilitada.

  • Versión de IP: HaVip solo es compatible con IPv4.

  • Recursos asociados:

    • Un HaVip se puede asociar únicamente con un tipo de recurso a la vez. Para cambiar de tipo, primero desasocie los recursos actuales.

    • Cuando asocie un HaVip con una ENI, asegúrese de que la ENI esté conectada a una instancia ECS.

    • Si se elimina una instancia ECS o una ENI asociada, el sistema desasocia automáticamente el HaVip de ese recurso.

    • Desconectar una ENI secundaria de una instancia ECS no afecta la asociación entre el HaVip y la ENI.

Console

Crear y asociar un HaVip

  1. Vaya a la página VPC Console - HaVip. Seleccione la región de sus instancias ECS y luego haga clic en Create HaVip.

  2. Seleccione la VPC y el vSwitch a los que pertenecen las instancias ECS. Puede asignar automáticamente una dirección IP privada desde el bloque CIDR del vSwitch o especificar una dirección IP no asignada.

  3. Instale Keepalived en las instancias ECS principal y en espera, y ejecute systemctl start keepalived para iniciar Keepalived.

    Ejemplo de instalación de Keepalived

    Este ejemplo instala Keepalived en instancias ECS basadas en CentOS dentro de un clúster de dos nodos con configuración principal/secundaria. Utilice Keepalived V1.2.15 o una versión posterior.

    Si tiene varias instancias ECS en espera, debe declarar las direcciones IP de todas las instancias pares en el parámetro unicast_peer de cada instancia ECS.
    Reporte problemas y consulte recursos de solución de incidencias en Keepalived GitHub .

    Configuración del servidor principal

    1. Inicie sesión en la instancia ECS principal.

    2. Ejecute yum install keepalived para instalar Keepalived.

    3. Ejecute vim /etc/keepalived/keepalived.conf para editar el archivo keepalived.conf.

      Este ejemplo muestra únicamente los parámetros que requieren modificación. Configure los valores según su instancia específica. No sobrescriba su archivo keepalived.conf actual con este ejemplo.
      ! Configuration File for keepalived
      vrrp_instance VI_1 {
          state MASTER            # Set as the primary instance.
          interface eth0          # The network interface controller (NIC) to which the virtual IP (VIP) address is bound. This example uses eth0.
          virtual_router_id 51    # The virtual_router_id of the primary/standby cluster. Different primary/standby clusters in the same Virtual Private Cloud (VPC) must have different virtual_router_id values.
          nopreempt               # Set to non-preemptive mode.
          priority 100            # The priority. A larger number indicates a higher priority. In this example, the priority is set to 100 to make this the primary instance.
          advert_int 1            # The interval, in seconds, for sending heartbeat packets. A small value can cause frequent failovers or a temporary split-brain due to network jitter. A large value can increase the failover time if the primary instance fails.
          authentication {
              auth_type PASS
              auth_pass 1111
          }
          unicast_src_ip 192.168.0.25     # The private IP address of this instance. This example uses 192.168.0.25.
          unicast_peer {
              192.168.0.26          # The private IP address of the peer instance. This example uses 192.168.0.26. If you have multiple standby ECS instances, list the IP address of each peer instance on a separate line without commas or other separators.
          }
          virtual_ipaddress {
              192.168.0.24          # The virtual IP address. Set this to the IP address of the HaVip. This example uses 192.168.0.24.
          }   
          garp_master_delay 1       # The delay, in seconds, to update the ARP cache after the instance becomes the primary.
          garp_master_refresh 5     # The interval, in seconds, for sending ARP packets.
      
          track_interface {
              eth0                  # The NIC bound to the VIP address. This example uses eth0.
          }
      }
    4. Ejecute systemctl start keepalived para iniciar Keepalived.

    Configuración del servidor secundario

    1. Inicie sesión en la instancia ECS secundaria.

    2. Ejecute yum install keepalived para instalar Keepalived.

    3. Ejecute vim /etc/keepalived/keepalived.conf para editar el archivo keepalived.conf.

      Este ejemplo muestra únicamente las secciones que requieren modificación. Configure los valores según su instancia específica. No sobrescriba su archivo keepalived.conf actual con este ejemplo.
      ! Configuration File for keepalived
      vrrp_instance VI_1 {
          state BACKUP            # Set the instance as the secondary instance.
          interface eth0          # The NIC to which the VIP is bound. This example uses eth0.
          virtual_router_id 51    # The virtual_router_id of the primary/secondary cluster. Different primary/secondary clusters in the same VPC must have different virtual_router_id values.
          nopreempt               # Set to non-preemptive mode.
          priority 10             # The priority. A larger value indicates a higher priority. In this example, the priority is set to 10 to configure this instance as the secondary instance.
          advert_int 1            # The interval for sending heartbeat packets, in seconds. If this value is too small, the service is susceptible to network jitter, which can cause frequent failovers and temporary dual-primary scenarios (split-brain). If this value is too large, the failover time may be long after the primary instance fails.
          authentication {
              auth_type PASS
              auth_pass 1111
          }
          unicast_src_ip 192.168.0.26   # The private IP address of this instance. In this example, it is 192.168.0.26.
          unicast_peer {
              192.168.0.25          # The private IP address of the peer instance. In this example, it is 192.168.0.25. You must declare the IP addresses of all peer instances. Each address must be on a separate line, without commas or other separators.
          }
          virtual_ipaddress {
              192.168.0.24          # The virtual IP address. Set this to the IP address of the HaVip. In this example, it is 192.168.0.24.
          }    
          garp_master_delay 1       # The delay, in seconds, to update the ARP cache after this instance becomes the primary instance.
          garp_master_refresh 5     # The interval for sending ARP packets, in seconds.
      
          track_interface {
              eth0                  # The NIC to which the VIP is bound. This example uses eth0.
          }
      }
    4. Ejecute systemctl start keepalived para iniciar Keepalived.

  4. Haga clic en el ID del HaVip de destino. En la sección Resources, haga clic en Bind a la derecha de ECS Instances y seleccione las instancias ECS o ENI que desea asociar.

    Una vez completada la asociación, puede consultar el estado principal y secundario en la columna Associated Instance o en la sección Resources de la página de detalles.
  5. Compruebe el resultado:

    1. Ejecute los siguientes comandos en las instancias principal y secundaria para crear un servicio web de prueba que devuelva resultados distintos.

      Compruebe el uso del puerto ejecutando el comando netstat -an | grep 8000 . Si el puerto 8000 está ocupado, seleccione otro puerto.

      Instancia principal:

      echo "ECS 1" > index.html  # The primary instance returns "ECS 1"
      python3 -m http.server 8000

      Instancia secundaria:

      echo "ECS 2" > index.html  # The secondary instance returns "ECS 2"
      python3 -m http.server 8000
    2. Desde otra instancia ECS ubicada en la misma VPC, al ejecutar curl <havip_private_ip>:8000 se obtiene ECS 1. Después de que el servidor principal se detenga, devuelve ECS 2.

      Asegúrese de que los security groups de las instancias principal y secundaria permitan el tráfico HTTP desde la misma VPC hacia el puerto 8000.

Desasociar recursos

Haga clic en el ID del HaVip de destino. En la sección Resources, busque la instancia ECS o la interfaz de red elástica de destino en la lista de recursos Associated y haga clic en Delete Association.

Eliminar un HaVip

Antes de eliminar un HaVip, asegúrese de que no esté asociado con ninguna instancia ECS, ENI ni EIP. En la columna Actions del HaVip de destino, o en su página de detalles, haga clic en Delete.

API

Terraform

Recursos: alicloud_havip , alicloud_havip_attachment , alicloud_instance , alicloud_security_group , alicloud_security_group_rule
# Specify the region where you want to create the HaVip.
provider "alicloud" {
  region = "cn-hangzhou"
}

# Specify the ID of the VPC.
variable "vpc_id" {
  default = "vpc-bp1k******" # Replace with the actual ID of your VPC.
}

# Specify the vSwitch ID.
variable "vswitch_id" {
  default = "vsw-bp1y******" # Replace with the actual ID of your vSwitch.
}

# Specify the instance type.
variable "instance_type" {
  default = "ecs.e-c1m1.large"
}

# Specify the image ID.
variable "image_id" {
  default = "aliyun_3_x64_20G_alibase_20221102.vhd"
}

# Create an HaVip.
resource "alicloud_havip" "test_havip" {
  ha_vip_name = "test_havip_name"
  vswitch_id  = var.vswitch_id
  ip_address  = "192.168.0.24" # Specify an IP address for the HaVip from the vSwitch CIDR block. If not specified, the system assigns one.
}

# Create a security group.
resource "alicloud_security_group" "test_security_group" {
  security_group_name = "test_security_group_name"
  vpc_id              = var.vpc_id
}

# Create a security group rule. You need to adjust the protocol, source, and port based on your actual traffic.
resource "alicloud_security_group_rule" "allow_vpc_tcp" {
  type              = "ingress"
  ip_protocol       = "tcp"
  nic_type          = "intranet"
  policy            = "accept"
  port_range        = "8000/8000"
  priority          = 1
  security_group_id = alicloud_security_group.test_security_group.id
  cidr_ip           = "192.168.0.0/24"
}

# Create the primary server. 
resource "alicloud_instance" "test_master_instance" {
  instance_name        = "test_master_instance_name"
  vswitch_id           = var.vswitch_id
  instance_type        = var.instance_type
  image_id             = var.image_id
  system_disk_category = "cloud_essd"
  security_groups      = [alicloud_security_group.test_security_group.id]
  user_data = base64encode(<<-EOT
    #!/bin/sh
    yum install keepalived -y

    printf '! Configuration File for keepalived
    vrrp_instance VI_1 {
        state MASTER            # Set as the primary instance.
        interface eth0          # The network interface to which the virtual IP address is bound. This example uses eth0.  
        virtual_router_id 51    # The virtual_router_id of the primary/secondary cluster. Different clusters in the same VPC require different virtual_router_id values.
        nopreempt               # Set to non-preemptive mode.
        priority 100            # The priority. A higher value indicates a higher priority. This example sets the priority to 100 to make this instance the primary instance.
        advert_int 1            # The interval at which heartbeat messages are sent, in seconds. A small value makes the configuration susceptible to network jitter, which can cause frequent failovers or temporary split-brain scenarios. A large value can increase the failover time after the primary instance fails.
        authentication {
            auth_type PASS
            auth_pass 1111
        }
        unicast_src_ip 192.168.0.25     # The private IP address of this instance. This example uses 192.168.0.25.
        unicast_peer {
            192.168.0.26                # The private IP address of the peer instance. This example uses 192.168.0.26. If you have multiple secondary ECS instances, declare the IP address of each peer instance on a new line. Do not use commas or other separators.
        }
        virtual_ipaddress {
            192.168.0.24                # The virtual IP address. Set this to the HaVip's IP address. This example uses 192.168.0.24.
        }   
        garp_master_delay 1             # The delay in seconds before updating the ARP cache after a failover to this instance. 
        garp_master_refresh 5           # The interval at which ARP messages are sent, in seconds. 

        track_interface {
            eth0                        # The network interface to which the virtual IP address is bound. This example uses eth0.
        }
    }' > /etc/keepalived/keepalived.conf
    systemctl start keepalived
  EOT
  )                                           # Specify the initialization script for the primary server to install Keepalived.
  private_ip           = "192.168.0.25"       # Specify the private IP address of the primary server.
  instance_charge_type = "PostPaid"           # Set the billing method to pay-as-you-go.
  spot_strategy        = "SpotWithPriceLimit" # Set as a spot instance with a price limit.
}

# Create the secondary server. 
resource "alicloud_instance" "test_backup_instance" {
  instance_name        = "test_backup_instance_name"
  vswitch_id           = var.vswitch_id
  instance_type        = var.instance_type
  image_id             = var.image_id
  system_disk_category = "cloud_essd"
  security_groups      = [alicloud_security_group.test_security_group.id]
  user_data = base64encode(<<-EOT
    #!/bin/sh
    yum install keepalived -y

    printf '! Configuration File for keepalived
    vrrp_instance VI_1 {
        state BACKUP            # Set as the secondary instance.
        interface eth0          # The network interface to which the virtual IP address is bound. This example uses eth0.  
        virtual_router_id 51    # The virtual_router_id of the primary/secondary cluster. Different clusters in the same VPC require different virtual_router_id values.
        nopreempt               # Set to non-preemptive mode.
        priority 10             # The priority. A higher value indicates a higher priority. This example sets the priority to 10 to make this instance the secondary instance.
        advert_int 1            # The interval at which heartbeat messages are sent, in seconds. A small value makes the configuration susceptible to network jitter, which can cause frequent failovers or temporary split-brain scenarios. A large value can increase the failover time after the primary instance fails.
        authentication {
            auth_type PASS
            auth_pass 1111
        }
        unicast_src_ip 192.168.0.26   # The private IP address of this instance. This example uses 192.168.0.26.
        unicast_peer {
            192.168.0.25          # The private IP address of the peer instance. This example uses 192.168.0.25. If you have multiple secondary ECS instances, declare the IP address of each peer instance on a new line. Do not use commas or other separators.
        }
        virtual_ipaddress {
            192.168.0.24          # The virtual IP address. Set this to the HaVip's IP address. This example uses 192.168.0.24. 
        }    
        garp_master_delay 1       # The delay in seconds before updating the ARP cache after a failover to this instance. 
        garp_master_refresh 5     # The interval at which ARP messages are sent, in seconds. 

        track_interface {
            eth0                  # The network interface to which the virtual IP address is bound. This example uses eth0.
        }
    }' > /etc/keepalived/keepalived.conf
    systemctl start keepalived
  EOT
  )                                           # Specify the initialization script for the secondary server to install Keepalived.
  private_ip           = "192.168.0.26"       # Specify the private IP address of the secondary server. 
  instance_charge_type = "PostPaid"           # Set the billing method to pay-as-you-go.
  spot_strategy        = "SpotWithPriceLimit" # Set as a spot instance with a price limit.
}

# Associate with the primary server.
resource "alicloud_havip_attachment" "test_havip_attachment" {
  ha_vip_id   = alicloud_havip.test_havip.id
  instance_id = alicloud_instance.test_master_instance.id # Specify the ID of the instance to associate with the HaVip.
}

# Associate with the secondary server.
resource "alicloud_havip_attachment" "test_havip_attachment_new" {
  ha_vip_id   = alicloud_havip.test_havip.id
  instance_id = alicloud_instance.test_backup_instance.id # Specify the ID of the instance to associate with the HaVip.
}

Asociar una EIP para el acceso público

Un HaVip es una IP privada dentro de un vSwitch. Para habilitar el acceso a internet, asocie una dirección IP elástica (EIP) con el HaVip. Tenga en cuenta que EIPs incur fees.

1. La EIP debe estar disponible y ubicada en la misma región que el HaVip.
2. Cuando una instancia ECS accede a internet a través de una EIP asociada con un HaVip, la IP de origen de los paquetes salientes es la IP privada del HaVip, no la IP privada de la instancia ECS.

Console

Asociar o desasociar una EIP

Antes de asociar una EIP, cree una en la consola de EIP o haga clic en Create EIP en la página de asociación.

En la columna Actions del HaVip de destino, haga clic en Associate EIP o en Disassociate EIP.

API

Antes de asociar una EIP, llame a AllocateEipAddress para crearla.

Terraform

Recursos: alicloud_eip_address , alicloud_eip_association
# Specify the region of the HaVip. 
provider "alicloud" {
  region = "cn-hangzhou"
}

# Specify the ID of the HaVip.
variable "havip_id" {
  default = "havip-8vb0******"  # Replace with the actual ID of your HaVip.
}

# Create an EIP.
resource "alicloud_eip_address" "test_eip" {
  address_name = "test_eip_name"
  isp          = "BGP"
  netmode      = "public"
  bandwidth    = "1"
  payment_type = "PayAsYouGo"
}

# Associate the EIP.
resource "alicloud_eip_association" "test_eip_havip_association" {
  allocation_id = alicloud_eip_address.test_eip.id
  instance_type = "HAVIP"
  instance_id   = var.havip_id # Specify the ID of the HaVip.
}

Más información

Facturación

HaVip se encuentra en vista previa pública y no tiene costo. Durante este periodo no se proporciona ningún SLA.

Los recursos asociados, como ECS instances y EIPs, se facturan según sus respectivas reglas de precios.

Regiones compatibles

Área

Regiones

Asia Pacífico - China

China (Hangzhou), China (Shanghai), China (Nanjing - Local Region, Closing Down), China (Qingdao), China (Beijing), China (Zhangjiakou), China (Hohhot), China (Ulanqab), China (Shenzhen), China (Heyuan), China (Guangzhou), China (Chengdu), China (Zhongwei), China (Hong Kong), China (Wuhan - Local Region) y China (Fuzhou - Local Region, Closing Down)

Asia Pacífico - Otras

Japan (Tokyo), South Korea (Seoul), Singapore, Malaysia (Kuala Lumpur), Indonesia (Jakarta), Philippines (Manila), Thailand (Bangkok) y Malaysia (Johor)

Europa y América

Germany (Frankfurt), UK (London), France (Paris), US (Silicon Valley), US (Virginia), Mexico y Brazil (São Paulo)

Medio Oriente

UAE (Dubai) y Saudi Arabia (Riyadh - Partner Region)

Cuotas

HaVip se encuentra en vista previa pública. Para habilitarlo, inicie sesión en la consola de Quota Center y envíe una solicitud.

Nombre de la cuota

Descripción

Límite predeterminado

Ajustable

Ninguna

Tipo de red compatible con HaVip.

VPC

No

Número máximo de HaVip por instancia ECS.

5

Número máximo de EIP por HaVip.

1

Número máximo de instancias ECS o interfaces de red elásticas (ENI) que se pueden asociar simultáneamente con un HaVip.

10

1. Un HaVip se puede asociar con hasta 10 instancias ECS o 10 ENI, pero no con ambos tipos al mismo tiempo.
2. Un HaVip solo se puede asociar con instancias ECS o ENI que estén en el mismo vSwitch que el HaVip.

Indica si los HaVip admiten comunicación de difusión (broadcast) y multidifusión (multicast).

No compatible

HaVip solo admite comunicación unicast. Si utiliza software de terceros como Keepalived para implementar alta disponibilidad, debe cambiar el modo de comunicación a unicast en el archivo de configuración.

vpc_quota_havip_custom_route_entry

Número máximo de entradas de ruta en una tabla de rutas cuyo destino sea un HaVip.

5

Sí. Para solicitar un aumento de cuota, vaya a la página de gestión de cuotas o al Quota Center.