lxc是一种系统层级的虚拟化方案,利用clone这个系统调用的一些特性,模拟一个虚拟化的场景(独立的网络、文件系统),并利用cgroup进行资源的限制管理。和常见的xen、kvm不同,它不是一种半虚拟化技术,他仅仅使用了本地cpu,只有一个传统意义上的操作系统。类似的解决方案有Solaris的Zone,在Freebsd的Jail。网络上关于ubuntu的lxc容器都有些小问题,所以整理一下希望对大家有些帮助,lxc的相关命令就不解释了,比较简单。
kernel
基本上kernel >= 2.6.27的linux下都已经在内核态支持lxc。
使用lxc-checkconfig进行检测
hoterran@hoterran-laptop:~$ sudo lxc-checkconfig Kernel config /proc/config.gz not found, looking in other places... Found kernel config file /boot/config-2.6.35-28-generic --- Namespaces --- Namespaces: enabled Utsname namespace: enabled Ipc namespace: enabled Pid namespace: enabled User namespace: enabled Network namespace: enabled Multiple /dev/pts instances: enabled --- Control groups --- Cgroup: enabled Cgroup namespace: enabled Cgroup device: enabled Cgroup sched: enabled Cgroup cpu account: enabled Cgroup memory controller: enabled Cgroup cpuset: enabled --- Misc --- Veth pair device: enabled Macvlan: enabled Vlan: enabled
确认每个选项都是enabled状态即可。
lxc tools
除了内核支持外还需要一些用户态的工具。
sudo apt-get install lxc bridge-utils debootstrap libcap-dev
另外bridge-utils搭建网桥的工具,debootstrap是用来搭建一个基本的debain容器系统的工具。
通过一下命令判断lxc是否安装正常。
hoterran@hoterran-laptop:~$ sudo lxc-execute -n test /bin/echo "hello world" hello world
如果你迫不及待想看看lxc的效果那么你可以试试如下的命令
/usr/bin/lxc-execute -n foo -f /usr/share/doc/lxc/examples/lxc-macvlan.conf /bin/bash
cgroups
cgroup是资源管理的关键。
mkdir /cgroup mount none -t cgroup /cgroup
bridges
网桥打通主机和容器的网络。
环境如下
192.169.1.* 是你的主机的地址,我们不去管他。
192.168.2.1 br网桥的地址,192.168.2.2 lxc容器的地址。
配置网桥,这里假定eth0作为连通的物理网卡,这里的eth0和后面的config.ubuntu文件要一一对应。
vim /etc/network/interfaces
auto br0 iface br0 inet static address 192.168.2.1 netmask 255.255.255.0 broadcast 192.168.2.255 gateway 192.168.2.1 bridge_ports eth0 bridge_stp off bridge_maxwait 5 post-up /usr/sbin/brctl setfd br0 0
是链路层面的交换,所有把ip给去掉。
ifconfig eth0 0.0.0.0
重启网络激活网桥
service networking stop service networking start
观察网桥的状况
hoterran@hoterran-laptop:~$ sudo brctl show bridge name bridge id STP enabled interfaces br0 8000.f0def12e0cdf no eth0
也可以通过brctl直接添加网桥,这个更简单。
lxc 容器的配置
创建容器的目录
mkdir /lxc cd lxc
先创建一个mini版的ubuntu系统
sudo debootstrap --variant=minbase --arch i386 lucid rootfs.ubuntu http://ubuntu.srt.cn/ubuntu ... ... ...
这里要等待一会,要下载大量的文件。
容器是简历在系统之上的,无法和驱动打交道没法认识到任何硬件,所以我们自己产生dev目录下的设备文件。
我们来编写一个脚本自动产生这些设备文件。
vim /usr/local/bin/lxc-config
ROOT=$(pwd) DEV=${ROOT}/dev if [ $ROOT = '/' ]; then printf "