Dockerfile:在构建期间创建和挂载磁盘映像

Dockerfile: create and mount disk image during build

我正在尝试在 Dockerfile 构建过程中构建和装载自定义磁盘映像:

FROM ubuntu:16.04
RUN dd if=/dev/zero of=foo.img count=500 bs=1M
RUN mkfs.ext4 foo.img
RUN mkdir -p /media/ext4disk
RUN mount -t ext4 foo.img /media/ext4disk

运行 docker build,我在最后一个命令中收到以下错误消息:mount failed: Unknown error -1

有什么方法可以实现我想做的事情吗?

您可能需要 docker run 具有的 --privileged--cap-add 功能,但 docker build 不支持这些功能。因此,从当前 Docker 版本开始,you can't.

this评论:

A significant number of docker users want the ability to --cap-add or --privileged in the build command, to mimic what is there in the run command.

That's why this ticket has been open for 3 years with people constantly chiming in even though the maintainers aren't interested in giving the users what they want in this specific instance.

作为替代方案,您可以将 RUN 命令移至容器启动​​时应该 运行 的脚本(并添加提到的 --privileged 标志,或 --cap-add=SYS_ADMIN

似乎您现在可以 运行 在构建模式下“不安全”:

检查文档:https://github.com/docker/buildx/blob/master/README.md#--allowentitlement

docker buildx create --use --name insecure-builder --buildkitd-flags '--allow-insecure-entitlement security.insecure'
docker buildx build --allow security.insecure -t my-image:latest .