Files
my-vault/01_Projects/Infrastructure/Services/docker network.md
T

89 lines
2.5 KiB
Markdown
Raw Normal View History

2026-01-05 13:03:55 +08:00
## Docker + firewalld + iptables 关系总结
### 1. 三者分工
- **iptables**:内核防火墙引擎,真正执行包过滤和 NAT。
- **firewalld**iptables 的“策略管理层”,按 **zone / service / masquerade** 等抽象生成规则。
- **Dockeriptables=true**:在 iptables 中写入 **容器相关** 的规则:
- 容器出网 SNATMASQUERADE
- 宿主端口 → 容器端口的 DNAT
- 容器网络之间的隔离(DOCKER-ISOLATION
三者是“共用 iptables,各管一摊”,不是互相替代。
---
### 2. Docker 关键配置项
`/etc/docker/daemon.json`
```json
{
"iptables": true,
"ip-masq": true
}
```
- `"iptables": true`(默认)
- Docker 创建/维护 DOCKER 链、端口映射、容器出网 NAT 等规则。
- 必须开启,否则大多数容器网络功能会坏(包括端口映射、bridge 容器出网)。
- `"iptables": false`
- Docker 不再改 iptables**不再创建 DOCKER/NAT 规则**。
- 需要你手工写所有 NAT / 端口映射规则。
- 常见现象:宿主机 & `--network host` 容器有网,但所有 bridge 容器出不了网。
- `"ip-masq": true`
- 为 Docker 私网(如 172.17.0.0/16)自动加 MASQUERADE,容器可用宿主 IP 出网。
---
### 3. firewalld 与 Docker 的协作方式
典型做法(推荐):
1. 保持 Docker 使用 iptables
```json
{
"iptables": true,
"ip-masq": true
}
```
2. 在 firewalld 里:
- 为 `docker0`、`br-xxxx` 等网桥分配到 `docker` zone
```bash
firewall-cmd --zone=docker --add-interface=docker0 --permanent
firewall-cmd --zone=docker --add-interface=br-xxxx --permanent
```
- 打开 masquerade 与 forward
```bash
firewall-cmd --zone=docker --add-masquerade --permanent
firewall-cmd --zone=docker --add-forward --permanent
firewall-cmd --reload
```
**原则:**
- Docker 负责:**容器内部路由 + NAT + 端口映射的具体规则**;
- firewalld 负责:**哪些接口/zone 允许转发、伪装、对外开放哪些端口**。
---
### 4. 典型坑点(本次踩到的)
- 设置:
```json
{
"iptables": false
}
```
- 结果:
- 宿主机有网;
- `--network host` 容器有网;
- 所有 bridge 网络容器无外网、访问 LE 超时。
- 根因:
- Docker 停止管理 iptables,不再生成容器 NAT 规则;
- firewalld 只负责 zone 和 masquerade,但**不知道容器网络细节**,无法替 Docker 完成 SNAT/端口映射。