Todos os produtos
Search
Central de documentação

Virtual Private Cloud:HaVip

Última atualização: Sep 22, 2026

Um endereço IP virtual de alta disponibilidade (HaVip) mantém o IP do serviço inalterado durante o failover entre instâncias ECS na mesma zona.

Por que usar um HaVip se o Keepalived já oferece alta disponibilidade para IPs virtuais?

Em data centers tradicionais, o Keepalived utiliza o VRRP para eleger uma nova instância primária durante o failover. A nova primária vincula o IP virtual à sua interface de rede e envia um broadcast ARP gratuito. Os demais dispositivos na LAN recebem esse broadcast e atualizam seus caches ARP para mapear o IP virtual ao endereço MAC da nova primária.

Provedores cloud utilizam redes definidas por software (SDN) e virtualização, onde a plataforma gerencia a alocação de IP. As aplicações não podem modificar IPs do host diretamente, e a rede virtual encerra o ARP na origem, impedindo que os hosts anunciem endereços IP. A Alibaba Cloud oferece o HaVip para resolver essa limitação.

Um HaVip é um IP privado gerenciado de forma independente. Defina o IP virtual do Keepalived como o endereço do HaVip e associe o HaVip a vários servidores. Quando o Keepalived elege uma nova primária, o sistema atualiza o mapeamento HaVip-instância — obtendo o mesmo efeito de um broadcast ARP gratuito e mantendo o IP do serviço inalterado durante o failover.

Como funciona

Um cluster de alta disponibilidade típico é composto por um HaVip e duas instâncias ECS em configuração primária/secundária:

  1. Configuração do Keepalived: associe o HaVip às instâncias ECS1 e ECS2 e instale o Keepalived em ambas. Defina virtual_ipaddress como o endereço do HaVip e atribua um valor de priority — a prioridade mais alta vence a eleição de primária.

  2. Eleição da primária: o Keepalived compara os valores de priority via VRRP e elege a instância com maior prioridade como primária. O sistema atualiza o mapeamento do HaVip, e todo o tráfego destinado ao HaVip é encaminhado para ECS1.

  3. Failover: ECS1 envia heartbeats para ECS2 no intervalo especificado por advert_int. Se ECS2 não receber um heartbeat dentro do tempo limite, o Keepalived promove ECS2 a primária. O sistema atualiza o mapeamento do HaVip para ECS2 e todo o tráfego é redirecionado — o IP do serviço permanece inalterado.

Para habilitar acesso público, associe o HaVip a um EIP. O tráfego passa então pelo EIP para fornecer serviços com alta disponibilidade voltados à internet.

image

Usar um HaVip para failover

Associe um HaVip a instâncias ECS ou interfaces de rede elásticas (ENIs) no mesmo vSwitch. Combinado com o Keepalived, isso mantém o IP do serviço inalterado durante o failover.

  • Cota: faça login no console do Quota Center e solicite a permissão de criação de HaVip. Um valor de cota igual a 1 indica que a criação de HaVip está habilitada.

  • Versão de IP: o HaVip suporta apenas IPv4.

  • Recursos associados:

    • Um HaVip pode ser associado a apenas um tipo de recurso por vez. Para alternar entre tipos, desassocie os recursos atuais primeiro.

    • Ao associar um HaVip a uma ENI, certifique-se de que a ENI esteja anexada a uma instância ECS.

    • Se uma instância ECS ou ENI associada for excluída, o sistema desassocia automaticamente o HaVip desse recurso.

    • Desanexar uma ENI secundária de uma instância ECS não afeta a associação entre o HaVip e a ENI.

Console

Criar e associar um HaVip

  1. Acesse a página VPC Console - HaVip. Selecione a região das suas instâncias ECS e clique em Create HaVip.

  2. Selecione a VPC e o vSwitch ao qual as instâncias ECS pertencem. Você pode atribuir automaticamente um endereço IP privado a partir do bloco CIDR do vSwitch ou especificar um endereço IP não utilizado.

  3. Instale o Keepalived nas instâncias ECS primária e secundária e execute systemctl start keepalived para iniciar o Keepalived.

    Exemplo de instalação do Keepalived

    Este exemplo instala o Keepalived em instâncias ECS baseadas em CentOS em um cluster primário/secundário de dois nós. Utilize o Keepalived V1.2.15 ou posterior.

    Se você tiver várias instâncias ECS secundárias, declare os endereços IP de todas as instâncias pares no unicast_peer de cada instância ECS.
    Reporte problemas e encontre recursos de solução de problemas no Keepalived GitHub .

    Configuração do Servidor Primário

    1. Faça login na instância ECS primária.

    2. Execute yum install keepalived para instalar o Keepalived.

    3. Execute vim /etc/keepalived/keepalived.conf para editar o arquivo keepalived.conf.

      Este exemplo mostra apenas os parâmetros que precisam de modificação. Configure de acordo com sua instância específica. Não sobrescreva o arquivo keepalived.conf existente com este exemplo.
      ! 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. Execute systemctl start keepalived para iniciar o Keepalived.

    Configuração do Servidor Secundário

    1. Faça login na instância ECS secundária.

    2. Execute yum install keepalived para instalar o Keepalived.

    3. Execute vim /etc/keepalived/keepalived.conf para editar o arquivo keepalived.conf.

      Este exemplo mostra apenas as seções que precisam de modificação. Configure de acordo com sua instância específica. Não sobrescreva o arquivo keepalived.conf existente com este exemplo.
      ! 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. Execute systemctl start keepalived para iniciar o Keepalived.

  4. Clique em o ID do HaVip desejado. Na seção Resources, clique em Bind à direita de ECS Instances e selecione as instâncias ECS ou ENIs a serem associadas.

    Após concluir a associação, você pode verificar o status primário e secundário na coluna Associated Instance ou na seção Resources da página de detalhes.
  5. Verifique o resultado:

    1. Execute os comandos a seguir nas instâncias primária e secundária para criar um serviço web de teste que retorna resultados diferentes.

      Verifique o uso da porta executando o comando netstat -an | grep 8000 . Se a porta 8000 estiver ocupada, escolha outra porta.

      Instância primária:

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

      Instância secundária:

      echo "ECS 2" > index.html  # The secondary instance returns "ECS 2"
      python3 -m http.server 8000
    2. A partir de outra instância ECS na mesma VPC, ao executar curl <havip_private_ip>:8000 o retorno será ECS 1. Após a parada do servidor primário, o retorno será ECS 2.

      Certifique-se de que os grupos de segurança das instâncias primária e secundária permitam tráfego HTTP da mesma VPC na porta 8000.

Desassociar recursos

Clique em o ID do HaVip desejado. Na seção Resources, localize a instância ECS ou interface de rede elástica desejada na lista de recursos Associated e clique em Delete Association.

Excluir um HaVip

Antes de excluir um HaVip, confirme que ele não está associado a nenhuma instância ECS, ENI ou EIP. Na coluna Actions do HaVip desejado, ou na página de detalhes, clique em Delete.

API

Terraform

Recurso: 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.
}

Associar um EIP para acesso público

Um HaVip é um IP privado dentro de um vSwitch. Para habilitar o acesso à internet, associe um Elastic IP Address (EIP) ao HaVip. Observe que EIPs incur fees.

1. O EIP deve estar na mesma região que o HaVip e estar disponível.
2. Quando uma instância ECS acessa a internet por meio de um EIP associado a um HaVip, o IP de origem dos pacotes de saída é o IP privado do HaVip, e não o IP privado da instância ECS.

Console

Associar ou desassociar um EIP

Antes de associar um EIP, crie um no console de EIP ou clique em Create EIP na página de associação.

Na coluna Actions do HaVip desejado, clique em Associate EIP ou Disassociate EIP.

API

Antes de associar um EIP, chame AllocateEipAddress para criar um.

Terraform

Recurso: 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.
}

Mais informações

Faturamento

O HaVip está em versão prévia pública e é gratuito. Nenhum SLA é fornecido durante a versão prévia pública.

Recursos associados como ECS instances e EIPs são cobrados de acordo com suas respectivas regras de precificação.

Regiões suportadas

Área

Regiões

Ásia-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) e China (Fuzhou - Local Region, Closing Down)

Ásia-Pacífico - Outros

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

Europa e Américas

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

Oriente Médio

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

Cotas

O HaVip está em versão prévia pública. Para habilitá-lo, faça login no console do Quota Center e envie uma solicitação.

Nome da cota

Descrição

Limite padrão

Ajustável

Nenhum

O tipo de rede que suporta HaVips.

VPC

Não

Número máximo de HaVips por instância ECS.

5

Número máximo de EIPs por HaVip.

1

Número máximo de instâncias ECS ou interfaces de rede elásticas (ENIs) que podem ser associadas a um HaVip simultaneamente.

10

1. Um HaVip pode ser associado a até 10 instâncias ECS ou 10 ENIs, mas não a ambos simultaneamente.
2. Um HaVip pode ser associado apenas a instâncias ECS ou ENIs que estejam no mesmo vSwitch que o HaVip.

Se os HaVips suportam comunicação broadcast e multicast.

Não suportado

O HaVip suporta apenas comunicação unicast. Se você utiliza software de terceiros como o Keepalived para implementar alta disponibilidade, altere o modo de comunicação para unicast no arquivo de configuração.

vpc_quota_havip_custom_route_entry

Número máximo de entradas de rota em uma tabela de rotas cujo destino é um HaVip.

5

Sim. Para solicitar um aumento de cota, acesse a página de Gerenciamento de Cotas ou o Quota Center.