> For the complete documentation index, see [llms.txt](https://handbook.bsdcn.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://handbook.bsdcn.org/di-7-zhang-wang-luo/7.6.-dns.md).

# 7.6.DNS

DNS 可以理解为一本[电话簿](https://en.wikipedia.org/wiki/Telephone_directory)，其中将 IP 地址与主机名相互关联。

有三个文件负责管理 FreeBSD 系统如何与 DNS 交互。这三个文件是 [hosts(5)](https://man.freebsd.org/cgi/man.cgi?query=hosts\&sektion=5\&format=html)、[resolv.conf(5)](https://man.freebsd.org/cgi/man.cgi?query=resolv.conf\&sektion=5\&format=html) 和 [nsswitch.conf(5)](https://man.freebsd.org/cgi/man.cgi?query=nsswitch.conf\&sektion=5\&format=html)。

除非在 **/etc/nsswitch.conf** 文件中另有说明，FreeBSD 将首先查看 **/etc/hosts** 文件中的地址，然后查看 **/etc/resolv.conf** 文件中的 DNS 信息。

> **注意**
>
> [nsswitch.conf(5)](https://man.freebsd.org/cgi/man.cgi?query=nsswitch.conf\&sektion=5\&format=html) 文件指定了 nsdispatch（名称服务切换调度器）的运行方式。
>
> 在默认情况下，**/etc/nsswitch.conf** 文件中的 hosts 部分如下所示：
>
> ```sh
> hosts: files dns
> ```
>
> 例如，在使用 [nscd(8)](https://man.freebsd.org/cgi/man.cgi?query=nscd\&sektion=8\&format=html) 服务时，将该行更改为如下所示，即可更改优先级顺序：
>
> ```sh
> hosts: files cache dns
> ```

## 7.6.1. 本地地址

**/etc/hosts** 文件是简单的文本数据库，用于提供主机名到 IP 地址的映射。通过局域网连接的本地计算机，可以将其条目添加到此文件中，以简化命名，而无需设置 DNS 服务器。此外，**/etc/hosts** 还可以用于提供互联网名称的本地记录，从而减少查询外部 DNS 服务器的需求，特别是对于常访问的名称。

例如，如果在本地环境中有 [www/gitlab-ce](https://cgit.freebsd.org/ports/tree/www/gitlab-ce/) 的本地实例，可以将其添加到 **/etc/hosts** 文件中，如下所示：

```sh
192.168.1.150 git.example.com git
```

## 7.6.2. 配置域名服务器

FreeBSD 系统如何访问互联网域名系统（DNS）由 [resolv.conf(5)](https://man.freebsd.org/cgi/man.cgi?query=resolv.conf\&sektion=5\&format=html) 控制。

**/etc/resolv.conf** 中最常见的条目有：

| 条目           | 说明                                      |
| ------------ | --------------------------------------- |
| `nameserver` | 解析器应该查询的名称服务器的 IP 地址。服务器按顺序查询，最多可以列出三个。 |
| `search`     | 主机名查找的搜索列表。通常由本地主机名的域决定。                |
| `domain`     | 本地域名。                                   |

典型的 **/etc/resolv.conf** 文件如下所示：

```sh
search example.com
nameserver 147.11.1.11
nameserver 147.11.100.30
```

> **注意**
>
> 选项 `search` 和 `domain` 只能使用其中一个。

使用 DHCP 时，[dhclient(8)](https://man.freebsd.org/cgi/man.cgi?query=dhclient\&sektion=8\&format=html) 通常会根据从 DHCP 服务器接收到的信息重写 **/etc/resolv.conf**。

> **技巧**
>
> 如果当前正在配置的这台机器 **不是** DNS 服务器，可以使用 [local-unbound(8)](https://man.freebsd.org/cgi/man.cgi?query=local-unbound\&sektion=8\&format=html) 来提升 DNS 查询性能。
>
> 要在系统引导时启用它，请执行以下命令：
>
> ```sh
> # sysrc local_unbound_enable="YES"
> ```
>
> 要启动 [local-unbound(8)](https://man.freebsd.org/cgi/man.cgi?query=local-unbound\&sektion=8\&format=html) 服务，请执行以下命令：
>
> ```sh
> # service local_unbound start
> ```
