OpenVZ vlan in container

When using OpenVZ, getting the VLAN working properly inside the container can be a tricky.  This procedure will use a script hooked into OpenVZ to automate the management and creation of VLANs on a Centos 6.x host node running OpenVZ.

Prerequisits

  • The package vconfig must be installed
  • The package bridge-utils must be installed
  • Obviously, the network you are plugged into must support and have VLANs configured.

Procedure

Create a file named /usr/local/bin/vznetadd with this content

CONFIGFILE=/etc/vz/conf/$VEID.conf
. $CONFIGFILE

NETIFLIST=$(printf %s "$NETIF" |tr ';' '\n')
dev="eth0"
ip link set dev "$dev" up

if [ -z "$NETIFLIST" ]; then
echo >&2 "According to $CONFIGFILE, CT$VEID has no veth interface configured."
exit 1
fi

for iface in $NETIFLIST; do
bridge=
host_ifname=

echo "Iface is $iface"
for str in $(printf %s "$iface" |tr ',' '\n'); do
case "$str" in
bridge=*|host_ifname=*)
eval "${str%%=*}=\${str#*=}" ;;
esac
done

[ -n "$bridge" ] ||
bridge=vmbr0

vlan=`echo "$bridge" | sed s/vlan//`
target_if="eth0.$vlan"

echo "Creating $bridge on CT0"
brctl addbr "$bridge"
echo "Adding interface $host_ifname to bridge $bridge on CT0 for CT$VEID"
ip link set dev "$host_ifname" up
brctl addif "$bridge" "$host_ifname"
echo 1 >"/proc/sys/net/ipv4/conf/$host_ifname/proxy_arp"
echo 1 >"/proc/sys/net/ipv4/conf/$host_ifname/forwarding"

echo "Creating interface $target_if on CT0 for CT$VEID"
vconfig add "$dev" "$vlan"
echo "Adding interface $host_ifname to bridge $bridge on CT0 for CT$VEID"
ip link set dev "$target_if" up
brctl addif "$bridge" "$target_if"
echo 1 >"/proc/sys/net/ipv4/conf/$target_if/proxy_arp"
echo 1 >"/proc/sys/net/ipv4/conf/$target_if/forwarding"

ip link set dev "$bridge" up

done

exit 0

Create a new file /etc/vz/vznet.conf with this content

#!/bin/bash

EXTERNAL_SCRIPT=/usr/local/bin/vznetaddr.new

Set each of the files to executable with this command

chmod +x /usr/local/bin/vznetadd /etc/vz/vznet.conf

Now your openvz system should be configured to setup openvz containers into VLANS as specified in their configuration.

To add a VLAN interface to an OpenVZ container, create the network interface like this:

vzctl set 101 --netif_add eth0.34,,,,vlan34 --save

This sample assumes you are using VLAN ID 34.  The name of the bridge must start with vlan for the script above to find the VLAN ID.