制作 Ubuntu 20.04 Ext4 根文件系统镜像
在嵌入式开发或定制系统中,制作一个可用的根文件系统(Root Filesystem)镜像是常见需求之一。本文将详细介绍如何基于 Ubuntu 20.04 构建一个适用于 ARM 架构(如 arm64 或 armhf)的 ext4 格式根文件系统镜像,包括基础系统部署、chroot 环境搭建、软件安装和镜像压缩等完整过程。
一、准备工作
首先,从 Ubuntu 官方获取针对目标架构的最小系统包:
1. 下载 ubuntu-base
前往官方地址下载 ubuntu-base 包:
官网地址: https://cdimage.ubuntu.com/ubuntu-base/releases/20.04/release/
对应架构的 tar 包:
- arm64:
ubuntu-base-20.04.4-base-arm64.tar.gz
- armhf:
ubuntu-base-20.04.5-base-armhf.tar.gz
- arm64:
创建根文件系统目录并解压:
mkdir -p rootfs/ubuntu
tar -xpvf ubuntu-base-20.04.4-base-arm64.tar.gz -C rootfs/ubuntu/
二、配置 chroot 环境
1. 安装 QEMU 模拟器
sudo apt-get install qemu-user-static
拷贝 qemu 仿真器到目标架构根文件系统:
cd rootfs/ubuntu/
cp /usr/bin/qemu-aarch64-static ./usr/bin/
# 如果是 armhf 架构,则使用:
# cp /usr/bin/qemu-arm-static ./usr/bin/
2. 编写挂载脚本 mnt_ubuntu.sh
创建 mnt_ubuntu.sh
脚本:
cd ../../rootfs
vim mnt_ubuntu.sh
内容如下:
#!/bin/bash
mnt() {
echo "MOUNTING"
sudo mount -t proc /proc ${2}proc
sudo mount -t sysfs /sys ${2}sys
sudo mount -o bind /dev ${2}dev
sudo mount -o bind /dev/pts ${2}dev/pts
sudo chroot ${2}
}
umnt() {
echo "UNMOUNTING"
sudo umount ${2}proc
sudo umount ${2}sys
sudo umount ${2}dev/pts
sudo umount ${2}dev
}
if [ "$1" == "-m" ] && [ -n "$2" ] ;
then
mnt $1 $2
elif [ "$1" == "-u" ] && [ -n "$2" ];
then
umnt $1 $2
else
echo ""
echo "Either 1'st, 2'nd or both parameters were missing"
echo ""
echo "1'st parameter can be one of these: -m(mount) OR -u(umount)"
echo "2'nd parameter is the full path of rootfs directory(with trailing '/')"
echo ""
echo "For example: ch-mount -m /media/sdcard/"
echo ""
echo 1st parameter : ${1}
echo 2nd parameter : ${2}
fi
赋予可执行权限并进入环境:
chmod +x mnt_ubuntu.sh
./mnt_ubuntu.sh -m ubuntu/
三、在 chroot 中配置系统环境
在进入 chroot
环境后,执行以下命令配置基本环境:
echo "nameserver 114.114.114.114" > /etc/resolv.conf
echo "hi3798m" > /etc/hostname
echo "Asia/Shanghai" > /etc/timezone
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
安装常用工具和网络服务:
apt update
apt install vim openssh-server sudo net-tools iputils-ping rsyslog
apt install network-manager ifupdown ethtool
配置网络自动获取 IP:
echo auto eth0 > /etc/network/interfaces.d/eth0
echo iface eth0 inet dhcp >> /etc/network/interfaces.d/eth0
启用 root 用户登录:
echo "PermitRootLogin yes" >> /etc/ssh/sshd_config
passwd root
清理无用缓存:
apt autoremove
apt-get autoclean
apt-get clean
apt clean
最后退出 chroot:
exit
然后卸载挂载点:
./mnt_ubuntu.sh -u ubuntu/
四、创建 ext4 根文件系统镜像
1. 创建空镜像文件并格式化
mkdir ubuntu_rootfs
dd if=/dev/zero of=ubuntu_ext4_rootfs.img bs=1024 count=716800 # 大小约 700MB
mkfs.ext4 ubuntu_ext4_rootfs.img
2. 挂载镜像并复制根文件系统
mount ubuntu_ext4_rootfs.img ubuntu_rootfs/
cp ./ubuntu/* ./ubuntu_rootfs/ -af
umount ubuntu_rootfs
3. 优化和压缩镜像
e2fsck -p -f ubuntu_ext4_rootfs.img
resize2fs -M ubuntu_ext4_rootfs.img
五、总结
通过上述步骤,你已经成功构建了一个 Ubuntu 20.04 的 ext4 根文件系统镜像,适用于 arm64 或 armhf 架构的嵌入式设备或虚拟机系统部署。整个过程包括了基础系统下载、模拟器配置、软件安装、网络配置和镜像压缩,是一个标准的定制根文件系统制作流程。