netns
netns (网络命名空间) 是网络堆栈的另一个实例,它有自己的网络设备(链接)、IP 设置和防火墙规则。除了使用 netns 构建容器外,它们还可以用于获得比使用 VRF 更严格的隔离。
先决条件
本文描述的软件包和补丁在 Alpine edge 和 ≥3.19 版本中可用。
netns 管理
iproute2
可以使用 ip netns
命令对 Netns 进行临时管理。
# ip netns # ip netns add tenant1 # ip netns del tenant1 # ip netns exec tenant1 ip -br link
ifstate
IfState,一个声明式网络配置工具,自 IfState 1.9.0 起完全支持 netns。以下配置示例创建了一个 WireGuard 隧道和一个 VLAN 子接口。WireGuard 链接 wg0
和 VLAN 子接口被移动到 vpn
netns 中。
/etc/ifstate/config.yml 的内容
# root netns interfaces: - name: eth0 addresses: - 198.51.100.2/31 link: state: up kind: physical routing: routes: - to: 0.0.0.0/0 via: 198.51.100.1 rules: [] namespaces: # "vpn" netns vpn: interfaces: - name: eth0.42 addresses: - 192.0.2.1/25 link: state: up kind: vlan vlan_id: 42 link: eth0 # link to eth0 in root netns link_netns: null - name: wg0 addresses: - 192.0.2.254/30 link: state: up kind: wireguard # bind wireguard to the root netns bind_netns: null wireguard: private_key: !include /etc/wireguard/secret.key peers: - public_key: 3Eimby+9YtJwtx+peCsz6RiubRqAp+cATHNiGWsUsEU= endpoint: 203.0.113.42 persistent_keepalive_interval: 30 allowedips: - 0.0.0.0/0 routing: routes: - to: 0.0.0.0/0 dev: wg0 rules: []
基于 netns 的服务隔离
当运行 OpenRC 0.49.0-r1 或更高版本时,服务可以在 netns (以及 netns 内的 VRF) 中隔离运行。在大多数情况下,您可以在 /etc/conf.d
中为服务设置 $netns
变量。
netns 必须在服务启动之前创建!
netns 兼容的 initd 脚本
并非所有 initd 脚本都可能与 netns 兼容。一些与网络堆栈相关的软件包已被修补以支持 netns。
- ipset
- iptables
- nftables