chroot容器使用的是宿主机的Linux内核,因此chroot可以拉取各个版本的Linux发行版,只要其能运行在X86芯片上。
chroot 命令可以改变根目录的挂载位置。根目录改变了,根目录下的库文件、配置文件等也都改变了,所以能实现切换到另一套系统环境中的效果。
debootstrap 能够拉取一套最小根目录系统,配合chroot,就能创建一套全新的系统环境。
schroot 用于强化chroot,chroot只能使用root用户,而schroot可以使用普通用户。
注意:不能在x86上安装arm的chroot,因为chroot使用的是宿主机内核及指令。
获取最小文件系统
debootstrap是debian/ubuntu下的一个工具,用来构建一套基本的系统(根文件系统)。生成的目录符合Linux文件系统标准(FHS),即包含了/boot、/etc、/bin、/usr等目录,但它比发行版本的Linux体积小很多,当然功能也没那么强大,因此只能说是“基本的系统”。
# 安装工具
sudo apt install schroot debootstrap
sudo mkdir /opt/chroot/
cd /opt/chroot/
# x86-64上布置amd64
sudo debootstrap --arch=amd64 xenial schroot-pipelight https://mirrors.bfsu.edu.cn/ubuntu/
# x86-64上布置i386
sudo debootstrap --arch i386 xenial ubuntu1604-i386 http://mirrors.tuna.tsinghua.edu.cn/ubuntu
# arm64上布置armhf,分两步:第一步是下载;第二步是配置
sudo debootstrap --arch armhf --foreign focal /opt/ubuntu-armhf http://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/
sudo chroot "/opt/ubuntu-armhf" /debootstrap/debootstrap --second-stage
– foreign,在与主机架构不同时,指定该参数,可将过程分为下载和安装两部分,第二过程需要指定 --second-stage;
x86_64的芯片可以直接做32位和64的文件系统,是因为chroot内的软件指令无论是32位还是64位都能被x86_64芯片解析。
配置schroot
*.conf
文件名随便起:
sudo vim /etc/schroot/chroot.d/1.conf
ubuntu-1604
是进入chroot后要显示的chroot名,directory
是chroot的路径,aliases
指定别名:
[ubuntu-1604]
description=ubuntu-1604
type=directory
directory=/opt/chroot/schroot-pipelight
aliases=u16
users=kylin
groups=kylin
root-groups=root
personality=linux
# 可配置多字段
[test]
description=test
type=directory
directory=/opt/chroot/schroot-pipelight
aliases=test
users=kylin
groups=kylin
root-groups=root
personality=linux
配置chroot
# 进入chroot
schroot -c u16
# 配置国内源,这里配置了ubuntu-1604的北外源:
sudo vim /etc/apt/sources.list
deb http://mirrors.bfsu.edu.cn/ubuntu/ xenial main restricted universe multiverse
deb http://mirrors.bfsu.edu.cn/ubuntu/ xenial-updates main restricted universe multiverse
deb http://mirrors.bfsu.edu.cn/ubuntu/ xenial-backports main restricted universe multiverse
deb http://mirrors.bfsu.edu.cn/ubuntu/ xenial-security main restricted universe multiverse
# 配置中文环境
sudo apt install locales
sudo dpkg-reconfigure locales
#选择需要的语言编码,按空格键选中,多选后按回车键确定
# 配置系统级语言环境
sudo vim /etc/bash.bashrc
export LANG=zh_CN.UTF-8
使用chroot
# 在容器内,执行命令
schroot -c u16 # 不推荐,sudo chroot <最小系统目录>
cat /etc/release # 查看系统版本
# 在宿主机上,执行命令
schroot -c u16 echo "hello world!"
# 在容器内,使用图形化界面
xhost +
schroot -c u16
export DISPLAY=:0
sudo apt install xclock
xclock
# 在宿主机上,使用图形化界面
xhost +
schroot -c u16 -p xclock