容器跨主機通訊之NAT

2021-07-29 07:36:29 字數 2167 閱讀 5396

nat分為dnat和snat,更多看:

預設情況下,容器可以主動訪問到外部網路的連線,但是外部網路無法訪問到容器。

1,container -- > outside

容器所有到外部網路的連線,源位址都會被nat成本地系統的ip位址。這是使用 iptables 的源位址偽裝操作實現的。

$ sudo iptables -t nat -nl

[sudo] password for uta:

chain prerouting (policy accept)

target     prot opt source               destination

docker     all  --  0.0.0.0/0            0.0.0.0/0            addrtype match dst-type local

chain input (policy accept)

target     prot opt source               destination

chain output (policy accept)

target     prot opt source               destination

docker     all  --  0.0.0.0/0           !127.0.0.0/8          addrtype match dst-type local

chain postrouting (policy accept)

target     prot opt source               destination

masquerade  all  --  172.17.0.0/16        0.0.0.0/0

chain docker (2 references)

target     prot opt source               destination

return     all  --  0.0.0.0/0            0.0.0.0/0

上述規則將所有源位址在 172.17.0.0/16 網段,目標位址為其他網段(外部網路)的流量動態偽裝為從系統網絡卡發出。masquerade 跟傳統 snat 的好處是它能動態從網絡卡獲取位址。

2,container  < -- outside

容器允許外部訪問,可以在 docker run 時候通過 -p 或 -p 引數來啟用。

不管用那種辦法,其實也是在本地的 iptable 的 nat 表中新增相應的規則

$ sudo docker run -t -i --name test  -p --expose 22  ubuntu:16.10 /bin/bash

-p 使用時需要指定 --expose 選項,指定需要對外提供服務的埠

使用 docker run -p 自動繫結所有對外提供服務的容器埠,對映的埠將會從沒有使用的埠池中 (49000..49900) 自動選擇,你可以通過 docker ps 、docker inspect 或者 docker port 確定具體的繫結資訊。

$ sudo docker ps

container id        image               command             created              status              ports                   names

3dafeabdd79a        ubuntu:16.10        "/bin/bash"         about a minute ago   up about a minute   0.0.0.0:32768->22/tcp   test

可以看到,對外對映32768埠

在container內執行:

$ sockperf server --tcp -i 172.17.0.2 -p 22

在client執行:

$ sockperf throughput --tcp -i 129.107.126.89 -p 32768  -t 10

原理:client訪問host的ip,port;然後host的port對映到container的服務的port,然後返回。

Dcoker跨主機容器通訊之overlay

同樣是兩台伺服器 準備工作 設定容器的主機名 consul kv型別的儲存資料庫 key value docker01 02上 vim etc docker daemon.json vim etc docker daemon.json vim usr lib systemd system docke...

Docker容器跨主機通訊

兩台主機上的docker容器直接通過ip位址進行通訊 各項配置如下 docker version 1.13.1 ip資訊根據個人需求部署 主機1的ip位址為 192.168.1.128 主機2的ip位址為 192.168.1.129 為主機1上的docker容器分配的子網 172.17.1.0 24...

docker跨主機容器通訊

docker 網路模式詳解 路由器位址192.168.1.1用route n檢視 parent enp7s0的乙太網名用ifcofig查詢 apt install net tools iputils ping ydocker network create driver macvlan subnet ...