使用ovs+docker实现容器间vlan隔离

步骤

1. 环境准备

1
2
3
4
5
6
7
8
9
10
# 安装openvswitch
$ yum install -y openvswitch

#下载OpenvSwitch项目提供的支持Docker容器的辅助脚本ovs-docker:

$ wget https://github.com/openvswitch/ovs/raw/master/utilities/ovs-docker
$ chmod a+x ovs-docker

## 拉取busybox镜像
$ docker pull busybox:latest

2. 创建容器

1
2
$ docker run –itd –privileged=true –net=none –name box1 busybox:latest /bin/sh
$ docker run –itd –privileged=true –net=none –name box2 busybox:latest /bin/sh

3. 创建网桥

1
2
3
4
$ ovs-vsctl add-br br0
$ ovs-vsctl add-br br0
$ ip link set br0 up
$ ip link set br1 up

4. 关联网桥设置ip、vlan

1
2
3
4
5
# 将容器关联网桥br0,并设置ip、vlan
$ ./ovs-docker add-port br0 eth0 box1 --ipaddress=10.0.0.1/24 --gateway=10.0.0.253
$ ./ovs-docker set-vlan br0 eth0 box1 5
$ ./ovs-docker add-port br1 eth0 box2 --ipaddress=10.0.0.2/24 --gateway=10.0.0.253
$ ./ovs-docker set-vlan br1 eth0 box2 5

5. 连接网桥

1
2
3
4
5
6
7
# patch口连接网桥
$ ovs-vsctl add-port br0 patch0 -- set interface patch0 type=patch options:peer=patch1
$ ovs-vsctl add-port br1 patch1 -- set interface patch1 type=patch options:peer=patch0

# 设置trunk,这里直接跳过不设置
$ ovs-vsctl set port patch0 VLAN_mode=trunk trunk=5
$ ovs-vsctl set port patch1 VLAN_mode=trunk trunk=5

6. 查看ovs网桥的所有端口

1
$ ovs-vsctl show

7. 测试容器的连通性

1
2
3
4
# 测试容器的连通性: 此时能通
# docker exec -it box1 ping 10.0.0.2
$ docker exec -it box1 sh
$ ping 10.0.0.2

测试vlan隔离

1
2
3
4
5
# 设置Vlan的参数为:网桥名、容器内网口名、容器名、vlan号
$ sudo ovs-docker set-vlan br0 eth0 box1 100
$ sudo ovs-docker set-vlan br1 eth0 box2 200

# 测试容器的连通性: 此时不通

参考