configure network in lxc containers to access host system physical network devices

By | 30th June 2015

I was trying to configure containers to get IPs from dhcp and it was difficult. at last I found a way to do it and thanks to debian wiki it again solved my problem, the source to solutions :).

 

Step 1

Installing lxc containers
installing lxc in debian stretch aka testing

apt-get install lxc bridge-utils debootstrap

Step 2

Create a template. From my experience I was unable to create template of other OS’s than debian on debian. I didn’t go deep into the problem but to find templates check this directory.

/usr/share/lxc/templates and in /usr/share/lxcexamples of config files and other stuff is there.

To create a new template

lxc-create -n<container name> -t<template>

Step 3

After creating the template a random password is generated, copy that and change it after first login in to container.

To start a container
lxc-start -n <container>
To run the container in demon mode give -d option.

Step 4

Now let us check network part. Change the following files accordingly

This will create a new device and forward traffic using masquerade
/etc/network/interfaces
auto lxc-bridge-nat
iface lxc-bridge-nat inet static
bridge_ports none
bridge_fd 0
bridge_maxwait 0
address 192.168.100.1
netmask 255.255.0.0
up iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE

Uncomment the line
/etc/sysctl.conf
# Uncomment the next line to enable packet forwarding for IPv4
net.ipv4.ip_forward=1

And give the command to forward

echo 1 > /proc/sys/net/ipv4/ip_forward

edit container config file and add these lines

/var/lib/lxc/<container>/config

# Template used to create this container: /usr/share/lxc/templates/lxc-debian
# Parameters passed to the template:
# For additional config options, please look at lxc.container.conf(5)
lxc.network.type = empty
lxc.rootfs = /var/lib/lxc/builds/rootfs

# Common configuration
lxc.include = /usr/share/lxc/config/debian.common.conf

# Container specific configuration
lxc.mount = /var/lib/lxc/builds/fstab
lxc.utsname = builds
lxc.arch = amd64
lxc.autodev = 1
lxc.kmsg = 0

# networking
lxc.network.type = veth
lxc.network.flags = up
lxc.network.link = lxc-bridge-nat
lxc.network.name = brid0
# It is fine to be commented out
lxc.network.ipv4 = 192.168.100.10/24
# Change this
lxc.network.hwaddr = 00:11:22:33:44:01
lxc.network.ipv4.gateway = 192.168.100.1

and lastly add dhcp in containers interfaces file
/var/lib/lxc/<container>/rootfs/etc/network/interfaces
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp

That is it and container should get internet.
Sources:
https://wiki.debian.org/LXC/SimpleBridge
https://www.flockport.com/enable-lxc-networking-in-debian-jessie-fedora-and-others/
https://github.com/claudyus/LXC-Web-Panel/issues/74