7.10. 使用 /dev/fuse 访问更快的构建
您可以使用 /dev/fuse 设备配置 pod,以启用更快、更有效的容器镜像构建,特别是针对非特权用户。此设备允许非特权 pod 挂载覆盖文件系统,这可通过 Podman 等工具利用。
7.10.1. 为 pod 中的非特权构建配置 /dev/fuse 复制链接链接已复制到粘贴板!
通过将 /dev/fuse 设备公开给非特权 pod,您可以授予其在用户空间 (FUSE) 挂载中执行 Filesystem 的功能。这可以通过在 pod 定义中添加 io.kubernetes.cri-o.Devices: "/dev/fuse" 注解来实现。此设置允许 pod 中的非特权用户使用带有存储驱动程序的 podman 等工具,如 fuse-overlayfs,以安全且有效的方式模拟特权构建功能,而无需授予 pod 的完整特权访问权限。
流程
使用
/dev/fuse访问定义 pod:使用以下内容创建名为
fuse-builder-pod.yaml的 YAML 文件:apiVersion: v1 kind: Pod metadata: name: fuse-builder-pod annotations: io.kubernetes.cri-o.Devices: "/dev/fuse" spec: containers: - name: build-container image: quay.io/podman/stable command: ["/bin/sh", "-c"] args: ["echo 'Container is running. Use oc exec to get a shell.'; sleep infinity"] securityContext: runAsUser: 1000其中:
io.kubernetes.cri-o.Devices-
io.kubernetes.cri-o.Devices: "/dev/fuse"注解使 FUSE 设备可用。 image-
此注解指定一个容器,它使用包含
podman的镜像(如quay.io/podman/stable)。 args-
此命令使容器保持运行,以便您可以
exec到其中。 securityContext此注解指定一个以非特权用户运行容器的
securityContext(例如,runAsUser: 1000)。注意根据集群的安全上下文约束(SCC)或其他策略,您可能需要进一步调整
securityContext规格,例如,如果只有/dev/fuse无法满足fuse-overlayfs的操作要求时允许特定容量。
运行以下命令来创建 pod:
$ oc apply -f fuse-builder-pod.yaml
验证 Pod 是否在运行:
$ oc get pods fuse-builder-pod访问 pod 并准备构建环境:
在
fuse-builder-podpod 处于Running状态后,在build-container环境中打开一个 shell 会话:$ oc exec -ti fuse-builder-pod -- /bin/bash您现在已在容器内。因为默认的工作目录可能无法被非特权用户写入,所以更改到
/tmp等可写目录:$ cd /tmp$ pwd/tmp创建 dockerfile 并使用 Podman 构建镜像:
在 pod 的 shell 和
/tmp目录中,您现在可以创建一个Dockerfile,并使用podman构建容器镜像。如果fuse-overlayfs是默认或已配置的存储驱动程序,则 Podman 可能会因为可用的/dev/fuse设备而利用fuse-overlayfs。创建示例
Dockerfile:$ cat > Dockerfile <<EOF FROM registry.access.redhat.com/ubi9/ubi-minimal RUN microdnf install -y findutils && microdnf clean all RUN echo "This image was built inside a pod with /dev/fuse by user $(id -u)" > /app/build_info.txt COPY Dockerfile /app/Dockerfile_copied WORKDIR /app CMD ["sh", "-c", "cat /app/build_info.txt && echo '--- Copied Dockerfile ---' && cat /app/Dockerfile_copied"] EOF使用
podman构建镜像。-t标志标记镜像:$ podman build -t my-fuse-built-image:latest .您应该会看到执行构建步骤的 Podman。
可选:测试构建的镜像:
仍在
fuse-builder-pod中,您可以从刚才构建的镜像中运行容器:$ podman run --rm my-fuse-built-image:latest这应该输出
/app/build_info.txt文件的内容以及复制的 Dockerfile。退出 pod 并清理:
完成后,退出 pod 中的 shell 会话:
$ exit如果不再需要 pod,请删除它:
$ oc delete pod fuse-builder-pod删除本地 YAML 文件:
$ rm fuse-builder-pod.yaml