Libnetwork 提供一个原生 Go 实现的容器连接,是容器的网络。libnetwork 的目标是定义一个健壮的容器网络模型(Container Network Model),提供一个一致的编程接口和应用程序的网络抽象。
Libnetwork一开始的代码只是 libcontainer 和 Docker Engine 中网络部分代码的合并,Docker 官方的愿景是希望 libnetwork 能像 libcontainer 一样,成为一个多平台的容器网络基础包。
受之前的一个 [GitHub issue](https://github.com/docker/docker/issues/9983) 启
发,libnetwork 引入了容器网络模型(CNM)的概念,CNM 定义了三个新的术语,分别是网络沙箱、Endpoint、Network。网络沙箱
指的是在每一个容器中,将会有一个隔离的用于网络配置的环境。Endpoint 是一个网络接口,可用于某一网络上的交流。Network 是一个唯一的且可识别的 Endpoint组。
接下来,Docker 公司将会把 libnetwork 集成到 Docker Engine,并在 Docker CLI 中使用新的网络命令。具体的项目路线图读者可以参考 [GitHub](https://github.com/docker/libnetwork/blob/master/ROADMAP.md)。
**注意:**libnetwork 项目正在大力开发中,还不适合日常使用!
**使用示例:**
<pre class="brush:cpp ;toolbar: true; auto-links: false;">// Create a new controller instance
controller := libnetwork.New()
// Select and configure the network driver
networkType := "bridge"
driverOptions := options.Generic{}
genericOption := make(map[string]interface{})
genericOption[options.GenericData] = driverOptions
err := controller.ConfigureNetworkDriver(networkType, genericOption)
if err != nil {
return
}
// Create a network for containers to join.
// NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can make of
network, err := controller.NewNetwork(networkType, "network1")
if err != nil {
return
}
// For each new container: allocate IP and interfaces. The returned network
// settings will be used for container infos (inspect and such), as well as
// iptables rules for port publishing. This info is contained or accessible
// from the returned endpoint.
ep, err := network.CreateEndpoint("Endpoint1")
if err != nil {
return
}
// A container can join the endpoint by providing the container ID to the join
// api which returns the sandbox key which can be used to access the sandbox
// created for the container during join.
// Join acceps Variadic arguments which will be made use of by libnetwork and Drivers
_, err = ep.Join("container1",
libnetwork.JoinOptionHostname("test"),
libnetwork.JoinOptionDomainname("docker.io"))
if err != nil {
return
}</pre>