Files
docker_practice/17_ecosystem/17.4_buildah.md
2026-02-27 19:23:50 -08:00

89 lines
3.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 17.4 Buildah - 容器镜像构建工具
本节介绍 Buildah包括其基础概念应用场景以及基本指令
### Buildah 简介
Buildah 是一个用于构建 OCIOpen Container Initiative兼容格式容器镜像的开源命令行工具 Docker 需要一直运行的守护进程daemon不同Buildah 的设计初衷是无需守护进程daemonless即可工作并且也不强制要求 root 权限rootless这使得在持续集成/持续部署CI/CD环境中构建镜像时能够更加轻量且安全
Buildah Red Hat 主导开发通常和 PodmanSkopeo 一起使用被认为是构建运行和管理容器的一套现代化工具链在很多需要增强安全性和无需依赖守护进程的场景中Buildah `docker build` 命令的最佳替代方案
### 核心特性
- **无守护进程Daemonless**Buildah 直接通过系统调用拉取构建和推送镜像减少了单点故障的风险和资源开销
- **构建效率高**可以挂载镜像的根文件系统到本地并直接利用宿主机的工具对其进行操作非常灵活
- **兼容性**不仅支持处理传统的 Dockerfile还能完全兼容 OCIOpen Container Initiative标准和 Docker 格式
- ** Podman 集成**Podman 自身构建镜像的命令 `podman build` 底层实际上也是依赖 Buildah 库来实现的
### 安装 Buildah
在许多主流的 Linux 发行版中都可以通过包管理器直接安装 Buildah
Fedora/CentOS/RHEL 为例
```bash
$ sudo dnf install -y buildah
```
Ubuntu/Debian 为例需引入官方源后
```bash
$ sudo apt-get update
$ sudo apt-get -y install buildah
```
### 基础用法示例
#### 1. 从现有的 Dockerfile 构建镜像
Buildah 最常见的用法就是像 Docker 一样根据 `Dockerfile` 来构建镜像可以直接使用 `buildah bud`或者 `buildah build-using-dockerfile`命令
```bash
$ buildah bud -t my-app:latest .
```
可以看到在这点上它与 `docker build` 的体验完全一致
#### 2. 交互式从空镜像开始构建
除了使用 DockerfileBuildah 最强大的功能来自于它的交互式和脚本化构建机制我们可以从一个极简的镜像或基础镜像开始构建
```bash
# 获取一个基础镜像
$ container=$(buildah from alpine:latest)
# 获取挂载点,并查看其路径
$ mnt=$(buildah mount $container)
$ echo $mnt
/var/lib/containers/storage/overlay/xxx/merged
# 利用宿主机直接创建文件,而不需要在容器内部运行命令
$ echo "Hello Buildah" > $mnt/hello.txt
# 添加一些配置和命令
$ buildah config --cmd "cat /hello.txt" $container
# 将容器提交为镜像
$ buildah commit $container my-hello-image:latest
# 构建完成后可以卸载并清理容器上下文
$ buildah unmount $container
$ buildah rm $container
```
这种模式在自动化流水线中极为有用因为我们可以将上述过程编写成标准的 bash 脚本无需为了构建镜像而撰写只在其独立语法中运行的 Dockerfile 指令
#### 3. 查看和推送镜像
通过 `buildah images` 可以查看当前环境中的镜像推送镜像到外部 Registry 也十分安全方便
```bash
# 查看本地构建的镜像
$ buildah images
# 推送镜像到 Docker Hub注意需要先登录
$ buildah push my-hello-image:latest docker://docker.io/username/my-hello-image:latest
```
结合其无需特权和灵活脚本的优点Buildah 正变得越来越受到构建和分发 OCI 镜像的用户喜爱