環境說明
- 兩個虛擬機
- 操作系統Centos7
- DOcker版本1.8
腳本內容:
| 1 | # From http://goldmann.pl/blog/2014/01/21/connecting-docker-containers-on-multiple-hosts/ |
| 2 | # Edit this variable: the 'other' host. |
| 3 | REMOTE_IP=192.168.0.103 |
| 4 | |
| 5 | # Edit this variable: the bridge address on 'this' host. |
| 6 | BRIDGE_ADDRESS=172.17.43.1/24 |
| 7 | |
| 8 | # Name of the bridge (should match /etc/default/docker). |
| 9 | BRIDGE_NAME=docker0 |
| 10 | |
| 11 | # bridges |
| 12 | |
| 13 | # Deactivate the docker0 bridge |
| 14 | ip link set $BRIDGE_NAME down |
| 15 | # Remove the docker0 bridge |
| 16 | brctl delbr $BRIDGE_NAME |
| 17 | # Delete the Open vSwitch bridge |
| 18 | ovs-vsctl del-br br0 |
| 19 | # Add the docker0 bridge |
| 20 | brctl addbr $BRIDGE_NAME |
| 21 | # Set up the IP for the docker0 bridge |
| 22 | ip a add $BRIDGE_ADDRESS dev $BRIDGE_NAME |
| 23 | # Activate the bridge |
| 24 | ip link set $BRIDGE_NAME up |
| 25 | # Add the br0 Open vSwitch bridge |
| 26 | ovs-vsctl add-br br0 |
| 27 | # Create the tunnel to the other host and attach it to the |
| 28 | # br0 bridge |
| 29 | ovs-vsctl add-port br0 gre0 -- set interface gre0 type=gre options:remote_ip=$REMOTE_IP |
| 30 | # Add the br0 bridge to docker0 bridge |
| 31 | brctl addif $BRIDGE_NAME br0 |
| 32 | |
| 33 | ip link set br0 up |
| 34 | |
| 35 | # iptables rules |
| 36 | |
| 37 | iptables -t nat -F;iptables -F |
| 38 | ip route add 172.17.0.0/16 dev docker0 |
| 39 | # Enable NAT |
| 40 | iptables -t nat -A POSTROUTING -s 172.17.43.0/24 ! -d 172.17.43.0/24 -j MASQUERADE |
| 41 | # Accept incoming packets for existing connections |
| 42 | iptables -A FORWARD -o docker0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT |
| 43 | # Accept all non-intercontainer outgoing packets |
| 44 | iptables -A FORWARD -i docker0 ! -o docker0 -j ACCEPT |
| 45 | # By default allow all outgoing traffic |
| 46 | iptables -A FORWARD -i docker0 -o docker0 -j ACCEPT |
| 47 | |
| 48 | # Restart Docker daemon to use the new BRIDGE_NAME |
| 49 | service docker restart |
說明:
在不同主機上執行以上腳本,REMOTE_IP和BRIDGE_ADDRESS根據實際地址進行調整。
結果圖:


流程整理
1、關閉selinux
2、安裝openvswitch並啟動服務
3、添加docker0網橋,設置IP並激活該網橋
4、在ovs上添加網橋bro
5、設置該br0網橋類型及遠程訪問IP,實現與遠程IP點對點的連接
通過ovs-vsctl add-port br0 gre0 -- set interface gre0 type=gre options:remote_ip=$REMOTE_IP命令,ovs打通了br0與指定外網IP的訪問.
6、添加br0網橋到本地docker0,使容器也能夠訪問遠程IP
