Setup lxc on Debian

Using low-overhead virtualization methods like chroots, containers, etc. is a great way to gain most of the benefits of virtualization without the overhead of traditional hypervisor-based virtualization. Since 2011, lxc has become the standard, kernel-integrated lightweight virtualization method.

Setting Linux containers, or lxc, up on Debian is very straightforward:

Install lxc and bridge-utils

apt-get install lxc bridge-utils

Setup cgroup mount point

mkdir -p /cgroup
echo "cgroup /cgroup cgroup defaults 0 0" >> /etc/fstab
mount /cgroup

Make sure you have IP forwarding enabled

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

Modify your networking configuration

We'll setup an internal 10.0.0.1 network using dummy0 as the bridged device by adding the following to your /etc/network/interfaces:

auto dummy0
iface dummy0 inet static
  address 10.0.0.1
  netmask 255.255.255.0
 
auto br0
iface br0 inet static
  max_wait 0
  bridge_ports dummy0
  address 10.0.0.1
  netmask 255.255.255.0

Run the container setup script

Usage: lxc-debian.sh <distribution> <container-name> <container-number>

wget https://gist.github.com/raw/3008518/e3b87deb423ace3c67628fe501af79d46d9de04c/lxc-debian.sh
chmod +x lxc-debian.sh
./lxc-debian.sh wheezy test 2

Start the container and enter the console
(user and password are both root)

lxc-start -n test -d
lxc-console -n test

Optional: On the host, setup iptables rules to route to and from the container

This will route all traffic from the container out through the host's eth0, and route incoming traffic on port 10080/10443 on the host to port 80/443 on the container for a web server.

HOSTIP=$(ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}')
DESTIP=$(grep address /var/lib/lxc/test/rootfs/etc/network/interfaces | awk '{print $2}')
iptables -t nat -A POSTROUTING -s 10.0.0.1/24 -j SNAT --to-source $HOSTIP
iptables -t nat -A PREROUTING -m tcp -p tcp --dport 10022 -j DNAT -i eth0 --to-destination $DESTIP:80
iptables -t nat -A PREROUTING -m tcp -p tcp --dport 10443 -j DNAT -i eth0 --to-destination $DESTIP:443

2 thoughts on “Setup lxc on Debian

  1. agonyzt

    Very good job! This is exactly what I was looking for :) Most tutorials are either outdated, incomplete, or use a bridge without a dummy internal network. I reviewed the script and there's just a small typo:

    # Auto-generated hostname. Please do not remove this comment.
    192.168.0.$num $name

    It should be 10.0.0.$num $name

  2. admin Post author

    Thanks for the comment! I actually fixed the script shortly after I posted this, but didn't update the link to the gist revision. I have now updated the link to the correct revision.

Leave a Reply

Your email address will not be published. Required fields are marked *