树莓派Raspbian默认是支持LXC容器的,下面我们介绍一下在树莓派上创建并运行容器的过程。

1. 安装LXC相关的package

$ sudo apt-get install -y git lxc lxc-dev

2. 创建LXC网络相关配置文件,这样就配置LXC使能Bridge,容器的网络类型为veth,也就是为容器创建一个virtual ethernet的网络接口,并将这个网络接口加入到host的bridge里面去。

$ vi /etc/default/lxc-net
USE_LXC_BRIDGE="true"
$ mkdir -p ~/.config/lxc
$ vi ~/.config/lxc/default.conf
lxc.network.type = veth
lxc.network.flags = up
lxc.network.link = lxcbr0
lxc.network.name = eth0

3. 将 UID/GID mapping 加入到 default.conf,通过以下的映射,在容器里uid为0,对应到host里面,uid为100000。所以用户在容器里面有root权限,但是在host侧没有root权限。

$ echo "lxc.id_map = u 0 `grep $USER /etc/subuid | cut -f2 -d:` 65536" >> ~/.config/lxc/default.conf
$ echo "lxc.id_map = g 0 `grep $USER /etc/subgid | cut -f2 -d:` 65536" >> ~/.config/lxc/default.conf

此时 ~/.config/lxc/default.conf 的内容应该如下所示(the 100000 values come from the subordinate UID/GID files at /etc/sub[ug]id files):

lxc.network.type = veth
lxc.network.flags = up
lxc.network.link = lxcbr0
lxc.network.name = eth0
 
lxc.id_map = u 0 100000 65536
lxc.id_map = g 0 100000 65536

4. 将当前用户加入到 "lxcbr0" bridge的用户列表中

$ echo "$USER veth lxcbr0 10" | sudo tee -a /etc/lxc/lxc-usernet
pi veth lxcbr0 10
$

5. 运行 lxc 和 lxc-net 服务

$ sudo systemctl start lxc
$ sudo systemctl start lxc-net

6. 重启设备

7. 检查看lxc和lxc-net是否运行正常

 

$ systemctl status lxc
● lxc.service - LXC Container Initialization and Autoboot Code
   Loaded: loaded (/lib/systemd/system/lxc.service; enabled; vendor preset: enabled)
   Active: active (exited) since Fri 2018-07-13 20:29:56 UTC; 7s ago
     Docs: man:lxc-autostart
           man:lxc
  Process: 882 ExecStop=/usr/lib/arm-linux-gnueabihf/lxc/lxc-containers stop (code=exited, status=0/SUCCESS)
  Process: 1160 ExecStart=/usr/lib/arm-linux-gnueabihf/lxc/lxc-containers start (code=exited, status=0/SUCCESS)
  Process: 1158 ExecStartPre=/usr/lib/arm-linux-gnueabihf/lxc/lxc-apparmor-load (code=exited, status=0/SUCCESS)
 Main PID: 1160 (code=exited, status=0/SUCCESS)
      CPU: 58ms
 
$ systemctl status lxc-net
● lxc-net.service - LXC network bridge setup
   Loaded: loaded (/lib/systemd/system/lxc-net.service; enabled; vendor preset: enabled)
   Active: active (exited) since Fri 2018-07-13 20:14:31 UTC; 16min ago
  Process: 906 ExecStop=/usr/lib/arm-linux-gnueabihf/lxc/lxc-net stop (code=exited, status=0/SUCCESS)
  Process: 955 ExecStart=/usr/lib/arm-linux-gnueabihf/lxc/lxc-net start (code=exited, status=0/SUCCESS)
 Main PID: 955 (code=exited, status=0/SUCCESS)
      CPU: 93ms

 

8. 创建一个 LXC container,取名为 demo,使用的是“download”类型的容器模板

.

$ lxc-create -t download -n demo -- -d alpine -r 3.7 -a armhf
Setting up the GPG keyring
Downloading the image index
Downloading the rootfs
Downloading the metadata
The image cache is now ready
Unpacking the rootfs
 
---
You just created an Alpinelinux 3.7 armhf (20180723_13:02) container.
$

9. 用lxc-start启动容器后,用lxc-attach到容器的shell里面,可以继续安装应用程序比如gcc make