It’s now possible to use CNI (container networking interface) with lxc. Here is an example. This requires some recent upstream patches, so for simplicity let’s use the lxc packages for zesty in ppa:serge-hallyn/atom. Setup a zesty host with that ppa, i.e.
sudo add-apt-repository ppa:serge-hallyn/atom sudo add-apt-repository ppa:projectatomic/ppa sudo apt update sudo apt -y install lxc1 skopeo skopeo-containers jq
(To run the oci template below, you’ll also need to install git://github.com/openSUSE/umoci. Alternatively, you can use any standard container, the oci template is not strictly needed, just a nice point to make)
Next setup CNI configuration, i.e.
cat >> EOF | sudo tee /etc/lxc/simplebridge.cni { "cniVersion": "0.3.1", "name": "simplenet", "type": "bridge", "bridge": "cnibr0", "isDefaultGateway": true, "forceAddress": false, "ipMasq": true, "hairpinMode": true, "ipam": { "type": "host-local", "subnet": "10.10.0.0/16" } } EOF
The way lxc will use CNI is to call out to it using a start-host hook, that is, a program (hook) which is called in the host namespaces right before the container starts. We create the hook using:
cat >> EOF | sudo tee /usr/share/lxc/hooks/cni #!/bin/sh CNIPATH=/usr/share/cni CNI_COMMAND=ADD CNI_CONTAINERID=${LXC_NAME} CNI_NETNS=/proc/${LXC_PID}/ns/net CNI_IFNAME=eth0 CNI_PATH=${CNIPATH} ${CNIPATH}/bridge < /etc/lxc/simplebridge.cni EOF
This tells the ‘bridge’ CNI program our container name and the network namespace in which the container is running, and sends it the contents of the configuration file which we wrote above.
Now create a container,
sudo lxc-create -t oci -n a1 -- -u docker://alpine
We need to edit the container configuration file, telling it to use our new hook,
sudo sed -i '/^lxc.net/d' /var/lib/lxc/a1/config cat >> EOF | sudo tee -a /var/lib/lxc/a1/config lxc.net.0.type = empty lxc.hook.start-host = /usr/share/lxc/hooks/cni EOF
Now we’re ready! Just start the container with
lxc-execute -n a1
and you’ll get a shell in the alpine container with networking configured.
Disclaimer
The opinions expressed in this blog are my own views and not those of Cisco.
Reblogged this on brauner's blog and commented:
This was definitely needed! Thanks.
Cool that this feature landed. This is especially useful in conjunction with the OCI template you added.