在云平台中,网络实现网元与外界通信,而对于虚拟机或容器来说,其没有物理网卡,需要通过虚拟网卡与外界通过。在Linux环境中,network namespace实现了网络资源的隔离,它可以为网元提供网络设备(网卡)、ip配置等。下面我们来看看Linux环境下network namespace如何工作的。
network namespaces
network namespaces主要提供了关于网络资源的隔离,包括:网络设备、IPV4/IPV6协议栈、IP路由表、防火墙、/proc/net目录、/sys/class/net目录、套接字(socket)等
一个物理的网络设备最多存在于一个network namespace中,可通过veth-pair连接两个network namespace
默认情况下,物理网络设备都分配在最初的root namespace中
添加网络设备实践
下面与容器场景为例,我们创建两个container,两个container之间通过veth-pair(以太对)通信。对于虚拟机的场景也使用,只需要将container换成vm即可。
1. 如何为容器添加虚拟网卡(veth)
添加veth-pair到container
# 将容器的 network namespace 映射到主机中,从而我们可以直接在host上操作容器的 network namespace
# 其中 13816 为容器的 pid
mkdir /var/run/netns
ln -s /proc/13816/ns/net /var/run/netns/13816
# 将 veth0 放入容器中
ip link set veth0 netns 13816 up
ip netns exec 13816 ip a
2. 不同network namespace间通信:
2.1 利用简单的 veth-pair 实现通信