# 34.11.共用地址冗余协议（CARP）

## 34.11.1. 使用 CARP

通过在 **/boot/loader.conf** 中添加 **carp.ko** 内核模块的条目，启用 CARP 的启动时支持：

```sh
carp_load="YES"
```

要在不重启的情况下加载模块：

```sh
# kldload carp
```

对于偏好使用自定义内核的用户，在自定义内核配置文件中包含以下行，并按 [配置 FreeBSD 内核](https://docs.freebsd.org/en/books/handbook/kernelconfig/#kernelconfig) 中的说明编译内核：

```sh
device	carp
```

通过向 **/etc/rc.conf** 中添加条目来设置主机名、管理 IP 地址和子网掩码、共享 IP 地址以及 VHID。以下是 `hosta.example.org` 的示例：

```ini
hostname="hosta.example.org"
ifconfig_em0="inet 192.168.1.3 netmask 255.255.255.0"
ifconfig_em0_alias0="inet vhid 1 pass testpass alias 192.168.1.50/32"
```

下一组条目用于 `hostb.example.org`。由于它是第二个主机，因此使用不同的共享 IP 地址和 VHID。但是，使用 `pass` 指定的密码必须相同，因为 CARP 只会监听和接受来自具有正确密码的机器的通告。

```ini
hostname="hostb.example.org"
ifconfig_em0="inet 192.168.1.4 netmask 255.255.255.0"
ifconfig_em0_alias0="inet vhid 2 pass testpass alias 192.168.1.51/32"
```

第三台机器 `hostc.example.org` 配置为从任意主机处理故障转移。该机器配置了两个 CARP VHIDs，一个用于处理每个主机的虚拟 IP 地址。CARP 通告延迟（`advskew`）设置为确保备份主机的通告比主机稍后发出，因为 `advskew` 控制了当存在多个备份服务器时的优先级顺序。

```ini
hostname="hostc.example.org"
ifconfig_em0="inet 192.168.1.5 netmask 255.255.255.0"
ifconfig_em0_alias0="inet vhid 1 advskew 100 pass testpass alias 192.168.1.50/32"
ifconfig_em0_alias1="inet vhid 2 advskew 100 pass testpass alias 192.168.1.51/32"
```

配置两个 CARP VHIDs 后，`hostc.example.org` 将监控两个主机的状态。如果任何一个主机无法正常发送通告，备份服务器将接管共享 IP 地址，直到主机重新上线。

> **注意**
>
> 如果原主机重新上线，`hostc.example.org` 不会自动将虚拟 IP 地址归还给它。为了实现这一点，必须启用抢占功能。该功能默认禁用，可以通过 [sysctl(8)](https://man.freebsd.org/cgi/man.cgi?query=sysctl\&sektion=8\&format=html) 变量 `net.inet.carp.preempt` 来控制。管理员可以强制备份服务器将 IP 地址归还给主机：
>
> ```sh
> # ifconfig em0 vhid 1 state backup
> ```

完成配置后，可以重启网络服务或重启每台系统。高可用性现已启用。

CARP 功能可以通过多种 [sysctl(8)](https://man.freebsd.org/cgi/man.cgi?query=sysctl\&sektion=8\&format=html) 变量进行控制，详细信息请参阅 [carp(4)](https://man.freebsd.org/cgi/man.cgi?query=carp\&sektion=4\&format=html) 手册页。其他操作可以通过使用 [devd(8)](https://man.freebsd.org/cgi/man.cgi?query=devd\&sektion=8\&format=html) 从 CARP 事件触发。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://handbook.bsdcn.org/di-34-zhang-gao-ji-wang-luo/34.11.-gong-yong-di-zhi-rong-yu-xie-yi-carp.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
