天天看點

macvlan 網絡結構分析 - 每天5分鐘玩轉 Docker 容器技術(56)

上一節我們建立了 macvlan 并部署了容器,本節詳細分析 macvlan 底層網絡結構。

macvlan 不依賴 Linux bridge,<code>brctl show</code> 可以确認沒有建立新的 bridge。

檢視一下容器 bbox1 的網絡裝置:

除了 lo,容器隻有一個 eth0,請注意 eth0 後面的 <code>@if4</code>,這表明該 interface 有一個對應的 interface,其全局的編号為 <code>4</code>。根據 macvlan 的原理,我們有理由猜測這個 interface 就是主機的 enp0s9,确認如下:

可見,容器的 eth0 就是 enp0s9 通過 macvlan 虛拟出來的 interface。容器的 interface 直接與主機的網卡連接配接,這種方案使得容器無需通過 NAT 和端口映射就能與外網直接通信(隻要有網關),在網絡上與其他獨立主機沒有差別。目前網絡結構如圖所示:

macvlan 會獨占主機的網卡,也就是說一個網卡隻能建立一個 macvlan 網絡,否則會報錯:

但主機的網卡數量是有限的,如何支援更多的 macvlan 網絡呢?

好在 macvlan 不僅可以連接配接到 interface(如 enp0s9),也可以連接配接到 sub-interface(如 enp0s9.xxx)。

VLAN 是現代網絡常用的網絡虛拟化技術,它可以将實體的二層網絡劃分成多達 4094 個邏輯網絡,這些邏輯網絡在二層上是隔離的,每個邏輯網絡(即 VLAN)由 VLAN ID 區分,VLAN ID 的取值為 1-4094。

Linux 的網卡也能支援 VLAN(<code>apt-get install vlan</code>),同一個 interface 可以收發多個 VLAN 的資料包,不過前提是要建立 VLAN 的 sub-interface。

比如希望 enp0s9 同時支援 VLAN10 和 VLAN20,則需建立 sub-interface enp0s9.10 和 enp0s9.20。

在交換機上,如果某個 port 隻能收發單個 VLAN 的資料,該 port 為 Access 模式,如果支援多 VLAN,則為 Trunk 模式,是以接下來實驗的前提是:

enp0s9 要接在交換機的 trunk 口上。不過我們用的是 VirtualBox 虛拟機,則不需要額外配置了。

如果大家想了解更多 Linux VLAN 實踐,可參看 CloudMan 《每天5分鐘玩轉 OpenStack》中的相關章節。

下面示範如何在 enp0s9.10 和 enp0s9.20 上建立 macvlan 網絡。

首先編輯 host1 和 host2 的 /etc/network/interfaces,配置 sub-

auto enp0s9

iface enp0s9 inet manual

auto enp0s9.10

iface enp0s9.10 inet manual

vlan-raw-device enp0s9

auto enp0s9.20

iface enp0s9.20 inet manual

然後啟用 sub-interface:

ifup enp0s9.10

ifup enp0s9.20

建立 macvlan 網絡:

docker network create -d macvlan --subnet=172.16.10.0/24 --gateway=172.16.10.1 -o parent=enp0s9.10 mac_net10

docker network create -d macvlan --subnet=172.16.20.0/24 --gateway=172.16.20.1 -o parent=enp0s9.20 mac_net20

在 host1 中運作容器:

docker run -itd --name bbox1 --ip=172.16.10.10 --network mac_net10 busybox

docker run -itd --name bbox2 --ip=172.16.20.10 --network mac_net20 busybox

在 host2 中運作容器:

docker run -itd --name bbox3 --ip=172.16.10.11 --network mac_net10 busybox

docker run -itd --name bbox4 --ip=172.16.20.11 --network mac_net20 busybox

目前網絡結構如圖所示:

這四個容器之間的連通性如何?下一節我們将詳細讨論 macvlan 網絡的連通和隔離特性。

本文轉自CloudMan6 51CTO部落格,原文連結:http://blog.51cto.com/cloudman/1957217

繼續閱讀