Skip to content
LF Cert Trainer

Lesson 108 · Section 9: Networking

Lesson 108: CNI: the Container Network Interface

How CNI turned container networking into one contract: the runtime creates the namespace and calls a plugin, the plugin wires the interface and reports the address. What the specification says, which plugins exist, and how to run one by hand. · 15 min read · 4 min video

1/11CNI
0:00 / 4:03

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

What this lesson is about

In the last two lessons the same list of steps appeared twice: once typed by hand with ip netns and ip link, and once performed by Docker for its bridge network. Every program that starts containers needs those steps, and for a long time each one wrote its own code for them.

CNI, the Container Network Interface, ended that. It is a small specification that says how a container runtime asks a separate program, a plugin, to connect a container to a network. This lesson covers the standard itself:

  • What problem it solves and what it defines.
  • The duties of the runtime and of the plugin.
  • The configuration format, the operations, and the plugins that exist.

How the kubelet and containerd on a Kubernetes node find and use a plugin is the subject of a later lesson, CNI in Kubernetes. Here you learn the contract, so that lesson only has to show you the file locations.

Why it exists

Compare what different programs do when they start a container on a bridge network:

StepBy handDockerAny other runtime
1. Create a network namespaceip netns addyesyes
2. Create the bridge if it is missingip link add type bridgeyesyes
3. Create a veth pairip link add type vethyesyes
4. Attach one end to the bridgeip link set masteryesyes
5. Move the other end into the namespaceip link set netnsyesyes
6. Assign an IP address, add routesip addr add, ip route addyesyes
7. Bring the interfaces up, set up NATip link set up, iptablesyesyes

Steps 2 to 7 do not depend on who started the container. They could be one program, call it bridge, that takes a container ID and a namespace and does the rest:

bridge add 2e34dcf34 /var/run/netns/2e34dcf34

Now imagine a second kind of network, one that uses VLANs or a cloud provider's own routing. Without a standard, each runtime would have to add support for each kind of network: a matrix of M runtimes times N networks. With a standard, each runtime implements one call and each network vendor ships one program.

One contract between runtimes and network pluginscallscallscallsrunsrunsrunscontainerdruntimeCRI-OruntimePodmanruntimeCNIspec + JSON configbridgereference pluginCalicothird-party pluginCiliumthird-party plugin
One contract between runtimes and network plugins. Without CNI every runtime would need its own code for every kind of network. With CNI any runtime can use any plugin, because both sides follow the same specification.

Parts:

  • containerd (runtime)
  • CRI-O (runtime)
  • Podman (runtime)
  • CNI (spec + JSON config)
  • bridge (reference plugin)
  • Calico (third-party plugin)
  • Cilium (third-party plugin)

Connections:

  • containerd to CNI: calls
  • CRI-O to CNI: calls
  • Podman to CNI: calls
  • CNI to bridge: runs
  • CNI to Calico: runs
  • CNI to Cilium: runs

What CNI is

CNI is a project of the Cloud Native Computing Foundation. It consists of three things:

PartWhat it is
The specificationA document: the configuration format, the operations, how a runtime executes a plugin, and the result format
libcniA Go library that runtimes embed to read configuration and execute plugins
The reference pluginsA set of small plugins maintained by the project, such as bridge, host-local and portmap

The specification gives each side its duties.

The container runtime must:

  • Create the network namespace for the container.
  • Find the network configuration and decide which networks the container joins.
  • Execute the plugin with ADD when the container is created and with DEL when it is removed.
  • Pass the configuration as JSON.

The plugin must:

  • Be an executable that accepts the operations ADD, DEL, CHECK and VERSION.
  • Accept the container ID, the namespace path and the interface name as parameters.
  • Create the interface in the namespace and make sure the container gets an IP address and routes.
  • Print the result, or an error, in the specified JSON format.

How it works

The network configuration

A network is described by a JSON file:

{
  "cniVersion": "1.0.0",
  "name": "demonet",
  "type": "bridge",
  "bridge": "cni-demo0",
  "isGateway": true,
  "ipMasq": true,
  "ipam": {
    "type": "host-local",
    "subnet": "10.22.0.0/24",
    "routes": [{ "dst": "0.0.0.0/0" }]
  }
}
FieldMeaning
cniVersionThe version of the specification this file follows
nameThe name of the network. Must be unique on the host
typeThe plugin to run. It is the file name of the executable
bridge, isGateway, ipMasqOptions of this plugin: the bridge to use, give the bridge an address so it can be the gateway, masquerade traffic that leaves the range
ipamWhich plugin manages addresses, and its options

Most real files use the list form, with the extension .conflist. It names several plugins that run one after another for the same container:

{
  "cniVersion": "1.0.0",
  "name": "demonet",
  "plugins": [
    {
      "type": "bridge",
      "bridge": "cni-demo0",
      "isGateway": true,
      "ipMasq": true,
      "ipam": { "type": "host-local", "subnet": "10.22.0.0/24", "routes": [{ "dst": "0.0.0.0/0" }] }
    },
    { "type": "portmap", "capabilities": { "portMappings": true } }
  ]
}

The first plugin creates the interface. Each following plugin receives the result of the one before it (as prevResult) and adds to it. Here portmap adds port forwarding rules for the address that bridge set up.

The call

The runtime passes parameters in environment variables and the configuration on standard input. The plugin answers on standard output.

VariableContent
CNI_COMMANDThe operation: ADD, DEL, CHECK, GC, STATUS or VERSION
CNI_CONTAINERIDA unique ID for the container, chosen by the runtime
CNI_NETNSThe path of the network namespace, for example /run/netns/demo
CNI_IFNAMEThe name the interface must have inside the container, usually eth0
CNI_PATHThe directories to search for plugin executables
CNI_ARGSOptional extra arguments as KEY=value;KEY=value
OperationWhat the plugin does
ADDConnects the container: creates the interface, assigns the address, prints the result
DELUndoes ADD and releases the address. Must succeed even when something is already gone
CHECKVerifies that the container's networking is still as ADD left it
GCCleans up leftovers of containers that no longer exist (specification 1.1)
STATUSReports whether the plugin is ready to serve ADD (specification 1.1)
VERSIONPrints the specification versions the plugin supports
What happens in one ADD callADDADDrecords the addressveth, address, routeprints on stdoutContainer runtimecreated the netnsbridge plugin/opt/cni/bin/bridgehost-localIPAM pluginResult JSONIPs, routes, DNSContainer netnseth0 10.22.0.2Address store/var/lib/cni/networks
What happens in one ADD call. The runtime owns the namespace and the timing. The plugin owns the wiring. An IPAM plugin, called by the first plugin, owns the addresses.

Parts:

  • Container runtime (created the netns)
  • bridge plugin (/opt/cni/bin/bridge)
  • host-local (IPAM plugin)
  • Result JSON (IPs, routes, DNS)
  • Container netns (eth0 10.22.0.2)
  • Address store (/var/lib/cni/networks)

Connections:

  • Container runtime to bridge plugin: ADD
  • bridge plugin to host-local: ADD
  • host-local to Address store: records the address
  • bridge plugin to Container netns: veth, address, route
  • bridge plugin to Result JSON: prints on stdout

IP address management

Handing out addresses is its own problem: no two containers may get the same one, and addresses must return to the pool when a container is removed. CNI keeps it out of the interface plugins. The ipam section of the configuration names a second plugin, and the first plugin delegates to it.

IPAM pluginHow it chooses an address
host-localFrom a range in the configuration. Remembers what it gave out in files on the node, under /var/lib/cni/networks/<name>/
dhcpAsks a DHCP server on the network. Needs a helper daemon on the node
staticUses the address written in the configuration

host-local means what it says: its memory is local to one host. Two nodes that are given the same range will hand out the same addresses. A cluster therefore needs either a different range per node or an IPAM that coordinates across nodes. The Pod Networking lesson and the IPAM lesson later in this section pick that up.

The result

On success the plugin prints what it did:

{
  "cniVersion": "1.0.0",
  "interfaces": [
    { "name": "cni-demo0", "mac": "4e:2f:91:0a:6c:11" },
    { "name": "veth5d0c2f1a", "mac": "ba:77:3e:c0:15:8d" },
    { "name": "eth0", "mac": "d6:8b:42:f1:09:3a", "sandbox": "/run/netns/demo" }
  ],
  "ips": [{ "interface": 2, "address": "10.22.0.2/24", "gateway": "10.22.0.1" }],
  "routes": [{ "dst": "0.0.0.0/0" }],
  "dns": {}
}

The runtime reads the address from ips. This is where the IP of a Kubernetes Pod comes from: the plugin reports it to the runtime, the runtime reports it to the kubelet, and the kubelet writes it to the Pod's status.

On failure the plugin exits with a non-zero code and prints an error object such as {"code": 7, "msg": "failed to find plugin \"bridg\" in path [/opt/cni/bin]"}.

The plugins

The families of CNI pluginschaineddelegates toInterface pluginsbridge, macvlan, ptpMeta pluginsportmap, tuningIPAM pluginshost-local, dhcpThird-partyCalico, Cilium, Flannel
The families of CNI plugins. An interface plugin creates the interface and delegates addresses to an IPAM plugin. Meta plugins run after it in a chain. Third-party plugins bundle all of this for a whole cluster.

Parts:

  • Interface plugins (bridge, macvlan, ptp)
  • Meta plugins (portmap, tuning)
  • IPAM plugins (host-local, dhcp)
  • Third-party (Calico, Cilium, Flannel)

Connections:

  • Interface plugins to Meta plugins: chained
  • Interface plugins to IPAM plugins: delegates to

The reference plugins are grouped by what they do:

FamilyPluginsJob
Interface ("main")bridge, macvlan, ipvlan, ptp, host-device, vlan, loopbackCreate or move an interface into the container
IPAMhost-local, dhcp, staticChoose the address
Metaportmap, bandwidth, tuning, firewallChange the result of an earlier plugin in the chain

Clusters normally use a third-party plugin that brings its own way of connecting nodes, its own IPAM and often network policy:

PluginKnown for
FlannelSimple overlay network. No network policy of its own
CalicoRouting with BGP or overlay, network policy
CiliumeBPF data plane, network policy, can replace kube-proxy
Weave NetOverlay with its own IPAM. No longer maintained, but still used in course material
Cloud plugins (Amazon VPC CNI, Azure CNI)Pod addresses taken directly from the cloud network

They all speak the same contract to the runtime, which is why you can choose among them freely when you build a cluster.

Under the hood · CNI next to CRI and CSI

Kubernetes has three such interfaces, and the exam curriculum names them together:

InterfaceBetweenFor
CRI, Container Runtime Interfacekubelet and container runtimeStarting and stopping Pods and containers (gRPC)
CNI, Container Network Interfacecontainer runtime and network pluginConnecting a Pod's namespace to the network (executables and JSON)
CSI, Container Storage InterfaceKubernetes and storage driverCreating, attaching and mounting volumes (gRPC)

The pattern is the same each time: Kubernetes defines what it needs and leaves how to a replaceable component. CNI is the only one of the three that is not specific to Kubernetes and the only one that works by executing a binary instead of calling a service.

Note the order of the calls for a Pod: the kubelet asks the runtime through CRI to create the Pod sandbox, and the runtime calls CNI. The kubelet itself does not execute CNI plugins.

Using it

Example · Run the bridge plugin by hand

Play the role of the runtime on any Linux machine that has the reference plugins in /opt/cni/bin (every Kubernetes node does).

sudo ip netns add demo                      # the runtime's duty: create the namespace

cat > demonet.conf <<'EOF'
{
  "cniVersion": "1.0.0",
  "name": "demonet",
  "type": "bridge",
  "bridge": "cni-demo0",
  "isGateway": true,
  "ipMasq": true,
  "ipam": { "type": "host-local", "subnet": "10.22.0.0/24", "routes": [{ "dst": "0.0.0.0/0" }] }
}
EOF

sudo CNI_COMMAND=ADD CNI_CONTAINERID=demo1 CNI_NETNS=/run/netns/demo \
     CNI_IFNAME=eth0 CNI_PATH=/opt/cni/bin /opt/cni/bin/bridge < demonet.conf

The plugin prints the result JSON shown earlier. Check what it built:

sudo ip netns exec demo ip -br addr
ip -br addr show cni-demo0
sudo ip netns exec demo ping -c 1 10.22.0.1
lo               DOWN
eth0@if9         UP             10.22.0.2/24
cni-demo0        UP             10.22.0.1/24
1 packets transmitted, 1 received, 0% packet loss

One command did everything that took a dozen ip commands in the Network Namespaces lesson.

Example · See where host-local remembers addresses

sudo ls /var/lib/cni/networks/demonet/
sudo cat /var/lib/cni/networks/demonet/10.22.0.2
10.22.0.2  last_reserved_ip.0  lock
demo1
eth0

One file per address in use, containing the container ID and interface that hold it. On a node that uses host-local, counting these files tells you how many Pod addresses are taken, and a stale file explains an address that is never reused.

Example · Disconnect with DEL and clean up

DEL takes the same parameters and the same configuration as ADD:

sudo CNI_COMMAND=DEL CNI_CONTAINERID=demo1 CNI_NETNS=/run/netns/demo \
     CNI_IFNAME=eth0 CNI_PATH=/opt/cni/bin /opt/cni/bin/bridge < demonet.conf
sudo ls /var/lib/cni/networks/demonet/
sudo ip netns del demo
sudo ip link del cni-demo0
last_reserved_ip.0  lock

The address file is gone, so the address is free again. The bridge itself stays, because other containers may still use it. That is why the last line removes it by hand.

Example · Ask a plugin which versions it supports

CNI_COMMAND=VERSION /opt/cni/bin/bridge
{"cniVersion":"1.1.0","supportedVersions":["0.1.0","0.2.0","0.3.0","0.3.1","0.4.0","1.0.0","1.1.0"]}

VERSION needs no namespace and no configuration, so it is a safe way to check that a binary exists, is executable and is new enough for the cniVersion in a configuration file.

Tricks

Common mistakes

  • Calling CNI a network. CNI moves no packets. It is the contract used to set up an interface. The plugin and the kernel carry the traffic.
  • Expecting the plugin to create the namespace. The runtime creates it and passes its path in CNI_NETNS.
  • Thinking the kubelet runs CNI plugins. The container runtime does, when the kubelet asks it for a Pod sandbox.
  • Assuming Docker supports CNI. Docker uses CNM. Kubernetes nodes use containerd or CRI-O.
  • Giving every node the same host-local range. Each node keeps its own records, so addresses repeat across nodes.
  • Confusing the plugin bridge with the bridge it creates. bridge is the executable. The Linux bridge it manages has the name given in the bridge field, cni0 by default.
  • Forgetting that a chain runs in order. In a .conflist the interface plugin comes first, and meta plugins such as portmap follow.

Recap

  • CNI is a specification, a library and a set of reference plugins for connecting containers to networks.
  • The runtime creates the namespace, reads a JSON configuration and executes the plugin with ADD and DEL.
  • The plugin creates the interface, obtains an address through an IPAM plugin and prints the result as JSON.
  • Parameters travel in CNI_* environment variables, the configuration on standard input.
  • Reference plugins: interface (bridge, macvlan, ipvlan), IPAM (host-local, dhcp, static) and meta (portmap, tuning). Clusters use third-party plugins such as Calico, Cilium or Flannel.
  • Docker does not implement CNI. On Kubernetes nodes, containerd or CRI-O calls the plugin.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.