4

lxc 初体验

 3 years ago
source link: https://blog.lilydjwg.me/2013/4/15/first-time-lxc.38857.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

lxc 初体验

本文来自依云's Blog,转载请注明。

Linux Containers 是一种系统级的虚拟化方案。其实也就是个增强型的 chroot,和 BSD 的 jail 差不多吧。

安装 lxc 以及 bridge-utils 软件包。后者是用来建立网络的。关于对内核的要求什么的请查阅此文。虽然其内容有些过时了,但是参考价值还是很高的。当然,一般新一点的通用内核都支持的啦。

然后想好在建立的 Container 里放什么系统。比如我用的 Funtoo,安装教程在这里。但其实大部分内容没什么用的。按照这里的指示下载一个合适的 stage3 包,并解压到一个目录中。portage 的安装等后续工作就不说了。

创建一个网桥并分配 IP 地址:

$ sudo brctl addbr br0
$ sudo ifconfig br0 192.168.10.1

由于我使用的是无线网络,因此不能使用一般教程中的方法将 eth0 加到网桥中去。建立个 NAT 好了:

echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward
sudo iptables -t nat -A POSTROUTING -s 192.168.10.0/24 -j MASQUERADE

按下边这样新建一个文本文件:

# Container 的名字
lxc.utsname = funtoo
# 网络类型。我使用的是 veth
lxc.network.type = veth
lxc.network.flags = up
# 刚刚建立的网桥名
lxc.network.link = br0
#lxc.network.hwaddr 不要乱写,会出错的!让 lxc 自己决定吧。
# IP 地址。和网桥同一网段即可
lxc.network.ipv4 = 192.168.10.2
lxc.network.name = eth0
# fstab 文件
lxc.mount = /home/lilydjwg/workspace/funtoo/funtoo_root/etc/fstab
# 新系统的根文件系统
lxc.rootfs = /home/lilydjwg/workspace/funtoo/funtoo_root
# tty 数量。如果不给出的话 lxc-console 是连不上去的
lxc.tty = 7

然后,修改 funtoo 里的配置文件啦。首先是/etc/fstab

none /home/lilydjwg/workspace/funtoo/funtoo_root/dev/pts devpts defaults 0 0
none /home/lilydjwg/workspace/funtoo/funtoo_root/proc    proc   defaults 0 0
none /home/lilydjwg/workspace/funtoo/funtoo_root/sys     sysfs  defaults 0 0
none /home/lilydjwg/workspace/funtoo/funtoo_root/dev/shm tmpfs  defaults 0 0
/home/lilydjwg/tmpfs /mnt bind 0 0

最后一行就是和主系统共享的目录啦。不过我这里没有生效 :-(

然后删掉/etc/mtab

修改/etc/inittab启动配置文件。lxc-start命令启动的那个终端会是 container 的/dev/console文件:

# TERMINALS
c1:12345:respawn:/sbin/agetty --noclear 38400 console linux
c2:2345:respawn:/sbin/agetty 38400 tty1 linux

ttyN 上的 agetty 可以留着,因为我已经分配了足够的 tty 给它们。使用lxc-console -t 3 -n funtoo就可以连上 tty3。

修改/etc/resolv.conf,配置一个 DNS 服务器。

删除/etc/runlevels/default下关于 udev 的项;udev 是不会工作的。

给新系统中的 root 设置个密码:

$ sudo chroot /path/to/funtoo/root/ /bin/bash
funtoo ~ # passwd

创建新的 container。注意创建之后那个配置文件就没有用了。lxc 会复制一份到/var/lib/lxc/funtoo/config,需要的时候可以改它。

$ sudo lxc-create -f /path/to/config/file -n funtoo

如果我没记错的话,现在就可以启动 funtoo 啦:

$ sudo lxc-start -n funtoo

不想它占用一个终端的话就加-d选项让它在后台跑吧。

不过这时候网络还没配置好。虽然 eth0 已经有 IP 地址了,也可以和主系统相互通讯,但是路由表仍需要手动加上,不然访问不了外网的。

funtoo ~ # route add -net 0.0.0.0 gw 192.168.10.1

然后就尽情地玩儿吧 :-)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK