当前位置: 首页 > 编程文章 >

使用Busybox和FROM scratch构建Docker基础镜像

使用Busybox和FROM scratch构建Docker基础镜像

作者:林知时间:2025-02-09 17:51:46浏览:379

本文介绍如何利用 busybox 1.28.1 版本结合 FROM scratch 机制从零构建 Docker 基础镜像。通过编译链接 BusyBox 模块生成 rootfs,并打包为 tar 文件,最终创建一个仅约 1MB 大小的极简 Linux 运行环境,深入理解 Docker 镜像底层原理。

本文目录收起

Docker基础镜像与Busybox简介

Docker 镜像通常以 FROM alpine 等现有镜像作为起点,但最原始的基础镜像究竟是如何诞生的?本文将演示如何使用 busybox 创建一个基础镜像,借此过程加深对 Docker 相关概念的理解。

什么是基础镜像(base image)

基础镜像是指那些在 Dockerfile 中未指定 FROM 指令,或以 FROM scratch 开头所构建出的镜像。例如 Alpine 是一个极小的 Linux 镜像,目前大小仅为 4M 左右。


[root@kong ~]# docker images |grep alpine
docker.io/alpine        latest       3fd9065eaf02    4 months ago    4.15 MB
[root@kong ~]#

其 Dockerfile 结构非常简单,仅包含三行代码,这便构成了一个典型的基础镜像示例。


FROM scratch
ADD rootfs.tar.xz /
CMD ["/bin/sh"]

在接下来的内容中,我们将模仿 Alpine 的做法,亲手创建一个属于自己的基础镜像。

busybox

概要说明

BusyBox 被誉为“嵌入式 Linux 的瑞士军刀”,这一称号源自其官方自我介绍。它将众多 Unix/Linux 下的通用功能整合到一个小型可执行文件中。尽管为了追求嵌入式场景下的极致体积优化,部分功能可能有所精简,但对于一般需求而言已完全足够。Alpine 正是基于 BusyBox 并增加了 apk 包管理等工具,从而成为风靡一时的轻量级镜像。BusyBox 是基于 GPL 协议用 C 语言开发的开源项目,当前稳定版本为 1.28.4。

宿主机器


[root@kong ~]# uname -a
Linux kong 3.10.0-693.el7.x86_64 #1 SMP Tue Aug 22 21:09:27 UTC 2026 x86_64 x86_64 x86_64 GNU/Linux
[root@kong ~]# cat /etc/redhat-release 
CentOS Linux release 7.4.1708 (Core) 
[root@kong ~]#

下载 busybox

此处可直接使用的最新二进制版本为 1.28.1。


[root@kong ~]# wget https://busybox.net/downloads/binaries/1.28.1-defconfig-multiarch/busybox-x86_64
--2026-05-25 04:51:20-- https://busybox.net/downloads/binaries/1.28.1-defconfig-multiarch/busybox-x86_64
Resolving busybox.net (busybox.net)... 140.211.167.122
Connecting to busybox.net (busybox.net)|140.211.167.122|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1001112 (978K)
Saving to: 'busybox-x86_64'
100%[==============================================================================================>] 1,001,112  19.3KB/s  in 30s  
2026-05-25 04:51:57 (32.4 KB/s) - 'busybox-x86_64' saved [1001112/1001112]
[root@kong ~]#

设定 busybox


[root@kong ~]# cp busybox-x86_64 /usr/local/bin/busybox
[root@kong ~]# chmod +x /usr/local/bin/busybox
[root@kong ~]# which busybox
/usr/local/bin/busybox
[root@kong ~]#

版本确认

输入 busybox 命令可查看版本信息及内置的 Linux 工具列表。仔细浏览后会发现,BusyBox 自称“瑞士军刀”实至名归;反之,若其他工具敢自称 Linux 中的 BusyBox,恐怕会引发争议。


[root@kong ~]# busybox
BusyBox v1.28.1 (2026-02-15 14:34:02 CET) multi-call binary.
BusyBox is copyrighted by many authors between 1998-2026.
Licensed under GPLv2. See source distribution for detailed
copyright notices.
Usage: busybox [function [arguments]...]
  or: busybox --list[-full]
  or: busybox --install [-s] [DIR]
  or: function [arguments]...
  BusyBox is a multi-call binary that combines many common Unix
  utilities into a single executable. Most people will create a
  link to busybox for each function they wish to use and BusyBox
  will act like whatever it was invoked as.
Currently defined functions:
  [, [[, acpid, add-shell, addgroup, adduser, adjtimex, arch, arp, arping, ash, awk, base64, basename, beep, blkdiscard, blkid,
  blockdev, bootchartd, brctl, bunzip2, bzcat, bzip2, cal, cat, chat, chattr, chgrp, chmod, chown, chpasswd, chpst, chroot, chrt,
  chvt, cksum, clear, cmp, comm, conspy, cp, cpio, crond, crontab, cryptpw, cttyhack, cut, date, dc, dd, deallocvt, delgroup,
  deluser, depmod, devmem, df, dhcprelay, diff, dirname, dmesg, dnsd, dnsdomainname, dos2unix, dpkg, dpkg-deb, du, dumpkmap,
  dumpleases, echo, ed, egrep, eject, env, envdir, envuidgid, ether-wake, expand, expr, factor, fakeidentd, fallocate, false,
  fatattr, fbset, fbsplash, fdflush, fdformat, fdisk, fgconsole, fgrep, find, findfs, flock, fold, free, freeramdisk, fsck,
  fsck.minix, fsfreeze, fstrim, fsync, ftpd, ftpget, ftpput, fuser, getopt, getty, grep, groups, gunzip, gzip, halt, hd, hdparm,
  head, hexdump, hexedit, hostid, hostname, httpd, hush, hwclock, i2cdetect, i2cdump, i2cget, i2cset, id, ifconfig, ifdown,
  ifenslave, ifplugd, ifup, inetd, init, insmod, install, ionice, iostat, ip, ipaddr, ipcalc, ipcrm, ipcs, iplink, ipneigh,
  iproute, iprule, iptunnel, kbd_mode, kill, killall, killall5, klogd, last, less, link, linux32, linux64, linuxrc, ln, loadfont,
  loadkmap, logger, login, logname, logread, losetup, lpd, lpq, lpr, ls, lsattr, lsmod, lsof, lspci, lsscsi, lsusb, lzcat, lzma,
  lzop, makedevs, makemime, man, md5sum, mdev, mesg, microcom, mkdir, mkdosfs, mke2fs, mkfifo, mkfs.ext2, mkfs.minix, mkfs.vfat,
  mknod, mkpasswd, mkswap, mktemp, modinfo, modprobe, more, mount, mountpoint, mpstat, mt, mv, nameif, nanddump, nandwrite,
  nbd-client, nc, netstat, nice, nl, nmeter, nohup, nproc, nsenter, nslookup, ntpd, nuke, od, openvt, partprobe, passwd, paste,
  patch, pgrep, pidof, ping, ping6, pipe_progress, pivot_root, pkill, pmap, popmaildir, poweroff, powertop, printenv, printf, ps,
  pscan, pstree, pwd, pwdx, raidautorun, rdate, rdev, readahead, readlink, readprofile, realpath, reboot, reformime,
  remove-shell, renice, reset, resize, resume, rev, rm, rmdir, rmmod, route, rpm, rpm2cpio, rtcwake, run-init, run-parts,
  runlevel, runsv, runsvdir, rx, script, scriptreplay, sed, sendmail, seq, setarch, setconsole, setfattr, setfont, setkeycodes,
  setlogcons, setpriv, setserial, setsid, setuidgid, sh, sha1sum, sha256sum, sha3sum, sha512sum, showkey, shred, shuf, slattach,
  sleep, smemcap, softlimit, sort, split, ssl_client, start-stop-daemon, stat, strings, stty, su, sulogin, sum, sv, svc, svlogd,
  swapoff, swapon, switch_root, sync, sysctl, syslogd, tac, tail, tar, taskset, tcpsvd, tee, telnet, telnetd, test, tftp, tftpd,
  time, timeout, top, touch, tr, traceroute, traceroute6, true, truncate, tty, ttysize, tunctl, ubiattach, ubidetach, ubimkvol,
  ubirename, ubirmvol, ubirsvol, ubiupdatevol, udhcpc, udhcpd, udpsvd, uevent, umount, uname, unexpand, uniq, unix2dos, unlink,
  unlzma, unshare, unxz, unzip, uptime, users, usleep, uudecode, uuencode, vconfig, vi, vlock, volname, w, wall, watch, watchdog,
  wc, wget, which, who, whoami, whois, xargs, xxd, xz, xzcat, yes, zcat, zcip
[root@kong ~]

构建Rootfs文件系统

创建 rootfs

在介绍镜像基础时,这张图已被反复引用。rootfs 是 Linux 中的重要概念,Alpine 的 Dockerfile 中也包含 ADD rootfs.tar.xz / 这样的语句。接下来我们将了解如何生成一个简单的 rootfs。

创建目录并进入


[root@kong ~]# mkdir rootfs
[root@kong ~]# cd rootfs/
[root@kong rootfs]#

创建 rootfs

执行如下语句


for module in `busybox --list-modules`
do
 mkdir -p `dirname "$module"`
 ln -sf /bin/busybox "$module"
done

执行日志


[root@kong rootfs]# for module in `busybox --list-modules`
> do
>  mkdir -p `dirname "$module"`
>  ln -sf /bin/busybox "$module"
> done
[root@kong rootfs]#

结果确认


[root@kong rootfs]# ls
bin linuxrc sbin usr
[root@kong rootfs]# find . -type d
.
./usr
./usr/bin
./usr/sbin
./sbin
./bin
[root@kong rootfs]#

将 busybox 拷贝至新创建的 ./bin 目录下。

至此,上述命令所需的链接对象已存在。


[root@kong rootfs]# cp /usr/local/bin/busybox bin/
[root@kong rootfs]# ls -l bin/busybox
-rwxr-xr-x. 1 root root 1001112 May 25 05:27 bin/busybox
[root@kong rootfs]#

创建 rootfs.tar

此处需注意相对路径的使用。后续的相对路径会展开至根目录 / 下,从而构建出新系统的 rootfs,这也是从零搭建 Linux(Linux from Scratch)的关键操作之一。


[root@kong rootfs]# tar cpf rootfs.tar .
tar: ./rootfs.tar: file is the archive; not dumped
[root@kong rootfs]#

简单说明:busybox –list-modules 列出了 BusyBox 的所有模块,以此为基础创建了一个小型的 rootfs。 [root@kong rootfs]# busybox –list-modules |wc -l 389 [root@kong rootfs]#

使用FROM scratch创建镜像

准备Dockerfile

准备一个一行的 Dockerfile


[root@kong rootfs]# vi Dockerfile
[root@kong rootfs]# cat Dockerfile 
From scratch
[root@kong rootfs]#

创建 base 镜像。由于未发现具体内容,因此未创建出具体镜像。另外,本文为了演示方便,直接在此处创建 Dockerfile,这并不是一个好主意。实际使用时请不要这样做,如果当前目录下有 100G 的文件,构建过程会无比缓慢,且不符合规范,无关物品需要清场。


[root@kong rootfs]# docker build -t busyboxbase:latest .
Sending build context to Docker daemon 2.415 MB
Step 1/1 : FROM scratch
 ---> 
No image was generated. Is your Dockerfile empty?
[root@kong rootfs]# docker images |grep busyboxbase
[root@kong rootfs]# 

from scracth

虽然有了 From 指令,但这个 scratch 可以 pull 吗?在目前的版本中,它已被作为一个保留名称处理。


[root@kong rootfs]# docker search scratch |grep 'an explicitly empty'
docker.io  docker.io/scratch              an explicitly empty image, especially for ...  407    [OK]    
[root@kong rootfs]# docker pull scratch
Using default tag: latest
Error response from daemon: 'scratch' is a reserved name
[root@kong rootfs]#

为此,我们在 Dockerfile 中添加一行无实际作用的指令,以便观察 scratch 到底是什么。


[root@kong rootfs]# vi Dockerfile 
[root@kong rootfs]# cat Dockerfile 
From scratch
MAINTAINER LiuMiao 
[root@kong rootfs]#

进行构建后,发现产生了一个 0 字节的镜像文件,这与 scratch 的原意相符。


[root@kong rootfs]# docker build -t busyboxbase:latest .
Sending build context to Docker daemon 2.415 MB
Step 1/2 : FROM scratch
 ---> 
Step 2/2 : MAINTAINER LiuMiao 
 ---> Running in b118fd7c73a7
 ---> 2074dc76c09e
Removing intermediate container b118fd7c73a7
Successfully built 2074dc76c09e
[root@kong rootfs]# docker images |grep busyboxbase
busyboxbase           latest       2074dc76c09e    14 seconds ago   0 B
[root@kong rootfs]#

至此,我们理解了 FROM scratch 确实不会添加任何额外内容。接下来,我们像 Alpine 那样添加如下两句。


ADD rootfs.tar /
CMD ["/bin/sh"]

我们的 Dockerfile 也是几乎一样的三行。


[root@kong rootfs]# cat Dockerfile 
From scratch
ADD rootfs.tar /
CMD ["/bin/sh"]
[root@kong rootfs]#

这样就创建了一个以 busybox 为基础、大小为 1M 的镜像。


[root@kong rootfs]# docker build -t busyboxbase:latest .
Sending build context to Docker daemon 2.415 MB
Step 1/3 : FROM scratch
 ---> 
Step 2/3 : ADD rootfs.tar /
 ---> 0fbb0c8c7579
Removing intermediate container 8311e96f456c
Step 3/3 : CMD /bin/sh
 ---> Running in efb85c4526bf
 ---> 02270c80a4e4
Removing intermediate container efb85c4526bf
Successfully built 02270c80a4e4
[root@kong rootfs]# docker images |grep busyboxbase
busyboxbase           latest       02270c80a4e4    9 seconds ago    1.01 MB
[root@kong rootfs]#

运行并使用

使用 docker run 发现此镜像所启动的容器并无异常之处。


[root@kong rootfs]# docker run --rm -it busyboxbase sh
/ # hostname
b7f9e9646746
/ # uname -a
Linux b7f9e9646746 3.10.0-693.el7.x86_64 #1 SMP Tue Aug 22 21:09:27 UTC 2026 x86_64 GNU/Linux
/ #

小结

这篇文章介绍了如何使用 busybox 结合 from scratch 机制创建 docker 的基础镜像以及相关原理。本文利用 busybox 1.28.1版本创建了一个1.01M的可用的基础镜像,从瑞士军刀到瑞士指甲刀,你可以继续优化到若干K都是可行的,但是到了10M以下其实应该更多考虑的是后续的扩展性和功能性的因素了。但是从另外的角度考虑,集成进来了那么多功能的同时,也将这些功能的不安定因素也集成进来了。利用from scratch机制,创建小并且依赖性少的上下文环境是非常有用的。

参考文献

https://docs.docker.com/develop/develop-images/baseimages/

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对本站的支持。如果你想了解更多相关内容请查看下面相关链接

上一篇
Docker容器日志查看:attach与logs命令详解

在Docker容器中,查看应用日志主要依赖docker attach和docker logs两个命令。前者用于实时连接容器的标准输入、输出和错误流,但需注意其会阻塞终端且可能导致容器退出;后者专门用于获取容器日志,支持按行数截取,是查看历史日志更安全便捷的方式。

下一篇
Docker安装MySQL 5.7并解决中文乱码及数据持久化教程

本文介绍在Docker环境中部署MySQL 5.7的完整流程,涵盖镜像拉取、容器创建及基础连接测试。针对插入中文报错问题,详细演示如何通过挂载宿主机配置文件修改客户端与服务端编码为utf8,并利用容器数据卷实现数据库文件、日志及配置的持久化管理,确保容器重建后数据不丢失。

相关文章

更多
Linux下制作给ARM开发板使用的文件系统

本文介绍在Linux环境下利用Busybox源码和交叉编译工具链,通过Shell脚本自动化构建适用于ARM开发板的根文件系统的流程。脚本涵盖目录清理、Busybox文件拷贝及NFS服务配置等关键步骤,支持用户自定义路径并集成测试代码,最终实现快速部署与调试。

2025.03.05 759
基于BusyBox构建最小根文件系统的完整步骤

本文详解使用BusyBox构建嵌入式Linux最小根文件系统的五个核心步骤。首先建立rootfs目录结构,接着通过静态编译BusyBox生成/bin、/sbin等基础命令并拷贝至目标目录。随后配置etc目录下的inittab、passwd、profile及rc.S脚本以初始化系统环境。然后从交叉编译工具链中复制必要的动态链接库至lib目录。最后通过静态创建或使用mdev机制构建dev目录中的设备节点,完成整个最小根文件系统的搭建。

2025.08.13 289
Docker制作Python运行环境基础镜像的方法步骤

本文介绍如何使用Docker和Ubuntu 16.04基础镜像制作包含Python 3.5的运行环境。通过编写Dockerfile,配置gcc、make等依赖并编译安装Python,最终构建出可复用的镜像。文中详细展示了从准备安装包到验证镜像功能的完整流程。

2026.06.10 150

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。