Ubuntu镜像定制化配置技巧
Cubic是专为Ubuntu设计的图形化ISO定制工具,基于chroot环境,支持安装/卸载软件、修改系统配置、添加用户等操作,生成符合Ubuntu标准的ISO文件。
安装步骤:添加Cubic的PPA源(sudo add-apt-repository ppa:cubic-wizard/releases),更新软件包列表后安装(sudo apt install cubic)。
基础流程:启动Cubic并选择原始Ubuntu ISO作为基础;进入chroot环境(无需手动挂载proc/sys等目录);通过apt命令安装所需软件(如sudo apt install vscode chromium-browser)或删除不必要的包(如sudo apt remove libreoffice);清理缓存(sudo apt clean、sudo rm -rf /var/lib/apt/lists/*)以减小镜像体积;生成自定义ISO(自动处理squashfs文件系统和MD5校验)。
优势:无需记忆复杂的命令,适合快速定制包含常用工具的开发或运维环境。
通过debootstrap创建最小化Ubuntu系统,再通过chroot进入该系统进行深度定制,最后打包为ISO或直接部署。
基础流程:安装必要工具(sudo apt install debootstrap squashfs-tools genisoimage isolinux xorriso);使用debootstrap创建基础系统(例如sudo debootstrap --arch amd64 focal /mnt/ubuntu http://archive.ubuntu.com/ubuntu/ focal);挂载必要的虚拟文件系统(sudo mount -t proc /proc /mnt/ubuntu/proc、sudo mount --rbind /sys /mnt/ubuntu/sys、sudo mount --make-rslave /mnt/ubuntu/sys);chroot进入系统(sudo chroot /mnt/ubuntu);在chroot环境中更新系统(apt update && apt upgrade -y)、安装软件、修改配置(如/etc/hosts、/etc/fstab);退出chroot并卸载虚拟文件系统;使用mksquashfs将系统打包为squashfs文件系统(sudo mksquashfs /mnt/ubuntu /mnt/livecd/casper/filesystem.squashfs);生成ISO文件(使用xorriso命令配置引导信息和文件结构)。
Systemback可将当前运行的Ubuntu系统制作成可启动的Live ISO,包含用户数据和已安装软件,适合快速复制现有环境。
基础流程:添加Systemback的PPA源(sudo add-apt-repository ppa:nemh/systemback),安装软件(sudo apt install systemback);打开Systemback,点击“Live system create”;选择镜像保存路径和名称,勾选“Include the user data files”(包含用户文件);点击“Create new”生成.sblive文件;使用Systemback内置工具将.sblive转换为.iso格式。
无论使用哪种工具,定制完成后都需清理缓存和临时文件:
apt clean(清理APT缓存)、apt autoremove(删除无用依赖)、rm -rf /tmp/*(删除临时文件);/var/log)、缓存目录(/var/cache)等不必要的文件;rm -rf /var/lib/apt/lists/*清除APT软件包列表,减少镜像冗余。若定制的是Docker镜像,采用多阶段构建可显著减小最终镜像大小:
ubuntu:slim作为基础,安装编译工具和依赖(FROM ubuntu:slim AS builder、RUN apt-get update && apt-get install -y build-essential);ubuntu:slim镜像(FROM ubuntu:slim、COPY --from=builder /app/target /app),仅保留运行所需的文件;build-essential和python3-dev,编译扩展模块;第二阶段仅复制编译后的应用和python3,最终镜像大小可减少50%以上。定制过程中需要频繁下载软件包,更换国内源可大幅提升速度:
sudo cp /etc/apt/sources.list /etc/apt/sources.bak);sudo nano /etc/apt/sources.list),替换为清华大学镜像源(deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ focal main restricted universe multiverse等);sudo apt update);通过预置文件(preseed或cloud-init)实现Ubuntu安装过程的自动化,避免手动选择语言、时区、分区等步骤:
/preseed/custom.seed文件,内容示例:d-i partman-auto/init_automatically_partition string lvm(自动使用LVM分区)、d-i pkgsel/include string vim git curl(安装指定软件);修改isolinux.cfg或grub.cfg,添加preseed/file=/cdrom/preseed/custom.seed参数;user-data),定义用户、SSH密钥、软件包安装等,例如:users: - name: ubuntu ssh_authorized_keys: - ssh-rsa AAAAB3...;将配置文件注入镜像,实现云端自动配置。/etc/apt/sources.list、/etc/fstab),便于出现问题时恢复;