5.4. 构建容器
Buildah 是在 Red Hat Enterprise Linux 中构建容器的主要工具,您可以在 Podman 中使用它来管理和运行您构建的容器。
先决条件
-
container-tools元数据包已安装。
流程
安装容器工具:确保 RHEL 系统上已安装必要的容器工具。container-tools 模块提供 Buildah、Podman 和 Skopeo。
sudo dnf install container-tools
$ sudo dnf install container-toolsCopy to Clipboard Copied! Toggle word wrap Toggle overflow 创建 Containerfile : Containerfile 定义构建容器镜像的说明。此文件指定基础镜像、要安装的任何软件、要应用的配置以及要运行的应用程序。例如:
FROM registry.redhat.io/ubi10/ubi-minimal RUN microdnf -y update && microdnf -y install COPY index.html /var/www/html/ EXPOSE 80 CMD ["httpd", "-DFOREGROUND"]
FROM registry.redhat.io/ubi10/ubi-minimal RUN microdnf -y update && microdnf -y install COPY index.html /var/www/html/ EXPOSE 80 CMD ["httpd", "-DFOREGROUND"]Copy to Clipboard Copied! Toggle word wrap Toggle overflow 使用 Buildah 构建容器镜像:在进入包含容器文件的目录后,使用
buildah bud(或podman build)构建镜像。cd /<path_to_container_file> buildah bud -t your_image_name:tag .
$ cd /<path_to_container_file> $ buildah bud -t your_image_name:tag .Copy to Clipboard Copied! Toggle word wrap Toggle overflow -
your_image_name:您的镜像的名称。 -
标签:镜像的标签(如 latest、1.0)。 -
.: 表示 Containerfile 位于当前目录中。
-
运行容器:构建镜像后,您可以使用
podman run命令从其中运行容器。podman run -d -p 8080:80 my-web-app
$ podman run -d -p 8080:80 my-web-appCopy to Clipboard Copied! Toggle word wrap Toggle overflow -
-d:以分离模式(在后台)运行容器。 -
-p 8080:80: 将主机上的端口 8080 映射到容器内的端口 80。 my-web-app:要运行的镜像名称。- 容器构建中的 heredocs 语法
您可以在 Containerfile 中使用
heredoc语法,以及 Red Hat Enterprise Linux 基础镜像,确保启用BuildKit。如果命令包含heredoc语法,则 Containerfile 会考虑下一行,直到行只包含 heredoc delimiter,作为同一命令的一部分。您可以使用heredocs,直接在 Containerfile 中的RUN或COPY等指令中嵌入多行字符串。这对基于 RHEL 的镜像特别有用,因为它无需为简单的任务创建单独的脚本文件,从而提高了可读性和可维护性。例如,常见的用例在单个
RUN指令中运行多个 shell 命令,以创建单个镜像层,避免&& \语法:
-
-
RUN <<EOF: << 信号是 heredoc 的开头,EOF是用户定义的分隔符。 -
<&
lt;EOF和最终EOF之间的行被视为 shell 执行的一个脚本。 -
整个块是单个
RUN指令,其效率更高且更易于阅读。