> 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-18-zhang-oci-rong-qi/18.7.-pei-zhi-wang-luo.md).

# 18.7.配置网络

容器网络使用网络地址转换（NAT）让 VNET jail 访问主机的网络。这通过 [pf(4)](https://man.freebsd.org/cgi/man.cgi?query=pf\&sektion=4\&format=html) 实现，因此必须加载包过滤器内核模块。

将 **/usr/local/etc/containers/pf.conf.sample** 中的修改整合到 **/etc/pf.conf**，并将出口接口宏设置为与你默认网络接口相匹配的接口。

```sh
# 将这些修改为你的带默认路由的接口
v4egress_if = "vtnet0"
v6egress_if = "vtnet0"

nat on $v4egress_if inet from <cni-nat> to any -> ($v4egress_if)
nat on $v6egress_if inet6 from <cni-nat> to !ff00::/8 -> ($v6egress_if)

rdr-anchor "cni-rdr/*"
nat-anchor "cni-rdr/*"
table <cni-nat>
```

`rdr-anchor` 与 `nat-anchor "cni-rdr/*"` 行以嵌套在 `cni-rdr` 之下的锚点实现端口重定向。其中 `nat-anchor "cni-rdr/*"` 行是将来自容器主机的连接重定向到容器内运行的服务所必需的，即使目标是 `localhost`（**127.0.0.1** 或 **::1**）。

启用并启动防火墙：

```sh
# service pf enable
# service pf start
```

将来自容器主机本机的连接重定向到容器内运行的服务，还需要启用本地重定向支持：

```sh
# sysctl net.pf.filter_local=1
```

修改 **/etc/sysctl.conf** 使此更改永久生效：

```sh
net.pf.filter_local=1
```
