mirror of
https://github.com/yeasy/docker_practice.git
synced 2026-03-11 12:21:17 +00:00
Add more tools
This commit is contained in:
88
17_ecosystem/17.4_buildah.md
Normal file
88
17_ecosystem/17.4_buildah.md
Normal file
@@ -0,0 +1,88 @@
|
||||
## 17.4 Buildah - 容器镜像构建工具
|
||||
|
||||
本节介绍 Buildah,包括其基础概念、应用场景以及基本指令。
|
||||
|
||||
### Buildah 简介
|
||||
|
||||
Buildah 是一个用于构建 OCI(Open Container Initiative)兼容格式容器镜像的开源命令行工具。与 Docker 需要一直运行的守护进程(daemon)不同,Buildah 的设计初衷是无需守护进程(daemonless)即可工作,并且也不强制要求 root 权限(rootless)。这使得在持续集成/持续部署(CI/CD)环境中构建镜像时能够更加轻量且安全。
|
||||
|
||||
Buildah 由 Red Hat 主导开发,通常和 Podman、Skopeo 一起使用,被认为是构建、运行和管理容器的一套现代化工具链。在很多需要增强安全性和无需依赖守护进程的场景中,Buildah 是 `docker build` 命令的最佳替代方案。
|
||||
|
||||
### 核心特性
|
||||
|
||||
- **无守护进程(Daemonless)**:Buildah 直接通过系统调用拉取、构建和推送镜像,减少了单点故障的风险和资源开销。
|
||||
- **构建效率高**:可以挂载镜像的根文件系统到本地,并直接利用宿主机的工具对其进行操作,非常灵活。
|
||||
- **兼容性**:不仅支持处理传统的 Dockerfile,还能完全兼容 OCI(Open 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. 交互式从空镜像开始构建
|
||||
|
||||
除了使用 Dockerfile,Buildah 最强大的功能来自于它的交互式和脚本化构建机制。我们可以从一个极简的镜像(或基础镜像)开始构建:
|
||||
|
||||
```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 镜像的用户喜爱。
|
||||
Reference in New Issue
Block a user