docker_practice/advanced_network/port_mapping.md

53 lines
1.9 KiB
Markdown
Raw Normal View History

## 映射容器端口到宿主主机的实现
2014-09-05 07:50:54 +00:00
2014-09-18 09:38:20 +00:00
默认情况下,容器可以主动访问到外部网络的连接,但是外部网络无法访问到容器。
2017-11-26 03:28:55 +00:00
2014-09-18 09:38:20 +00:00
### 容器访问外部实现
2017-11-26 03:28:55 +00:00
容器所有到外部网络的连接,源地址都会被 NAT 成本地系统的 IP 地址。这是使用 `iptables` 的源地址伪装操作实现的。
2014-09-05 07:50:54 +00:00
查看主机的 NAT 规则。
2017-11-26 03:28:55 +00:00
2017-11-22 03:13:23 +00:00
```bash
2014-09-18 09:38:20 +00:00
$ sudo iptables -t nat -nL
2014-09-05 07:50:54 +00:00
...
Chain POSTROUTING (policy ACCEPT)
target prot opt source destination
MASQUERADE all -- 172.17.0.0/16 !172.17.0.0/16
...
```
2017-11-26 03:28:55 +00:00
其中,上述规则将所有源地址在 `172.17.0.0/16` 网段目标地址为其他网段外部网络的流量动态伪装为从系统网卡发出。MASQUERADE 跟传统 SNAT 的好处是它能动态从网卡获取地址。
2014-09-05 07:50:54 +00:00
2014-09-18 09:38:20 +00:00
### 外部访问容器实现
2014-09-05 07:50:54 +00:00
容器允许外部访问,可以在 `docker run` 时候通过 `-p``-P` 参数来启用。
2014-09-18 09:38:20 +00:00
不管用那种办法,其实也是在本地的 `iptable` 的 nat 表中添加相应的规则。
2014-09-18 09:38:20 +00:00
使用 `-P` 时:
2017-11-26 03:28:55 +00:00
2017-11-22 03:13:23 +00:00
```bash
2014-09-18 09:38:20 +00:00
$ iptables -t nat -nL
2014-09-05 07:50:54 +00:00
...
Chain DOCKER (2 references)
target prot opt source destination
DNAT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:49153 to:172.17.0.2:80
2014-09-18 09:38:20 +00:00
```
使用 `-p 80:80` 时:
2017-11-26 03:28:55 +00:00
2017-11-22 03:13:23 +00:00
```bash
2014-09-18 09:38:20 +00:00
$ iptables -t nat -nL
2014-09-05 07:50:54 +00:00
Chain DOCKER (2 references)
target prot opt source destination
DNAT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:80 to:172.17.0.2:80
```
2017-11-26 03:28:55 +00:00
2014-09-05 07:50:54 +00:00
注意:
2017-11-26 03:28:55 +00:00
* 这里的规则映射了 0.0.0.0,意味着将接受主机来自所有接口的流量。用户可以通过 `-p IP:host_port:container_port` 或 `-p
IP::port` 来指定允许访问容器的主机上的 IP、接口等以制定更严格的规则。
2017-11-26 03:28:55 +00:00
* 如果希望永久绑定到某个固定的 IP 地址,可以在 Docker 配置文件 `/etc/default/docker` 中指定 `DOCKER_OPTS="--ip=IP_ADDRESS"`,之后重启 Docker 服务即可生效。