在 docker build 期间在主机上执行命令 [英] Execute command on host during docker build

查看:27
本文介绍了在 docker build 期间在主机上执行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建 Dockerfile 在构建映像时在主机上执行命令?

Is it possible to create Dockerfile that executes a command on host when image is being build?

现在我在做:

./script_that_creates_magic_file.sh
docker build .

使用 Dockerfile:

with Dockerfile:

FROM alpine
COPY magic_file

我希望能够做到:

docker build .

使用 Dockerfile:

with Dockerfile:

FROM alpine
# invoke script_that_creates_magic_file.sh on the host
COPY magic_file

当然,这个脚本和Dockerfile在同一个目录.

Of course, this script is in the same directory as Dockerfile.

推荐答案

(只是一个建议)

我们通常有以下结构来构建我们的 docker 镜像:

We usually have the following structure for building our docker images:

my-image/
├── assets
│   ├── entrypoint.sh
│   └── install.sh
├── build.sh
├── Dockerfile
├── README.md
└── VERSION

  • build.sh:这是你应该调用的 script_that_creates_magic_file.sh.其他常见任务包括下载所需文件或临时从主机复制 ssh 密钥.最后,这个脚本会调用 docker build .
  • Dockerfile:像往常一样,但是根据我们需要运行的命令数量,我们可能有一个 install.sh
  • install.sh:这是复制并在容器内运行,安装包,删除不必要的文件等.没有 100% 确定 - 我认为这种方法减少了层数,避免了多个单个 RUN
  • 中的命令
  • entrypoint.sh:容器的入口点.允许我们在容器启动时执行任务(如解析环境变量)并打印调试信息
    • build.sh: This is were you should invoke script_that_creates_magic_file.sh. Other common tasks involve downloading required files or temporarily copying ssh keys from the host. Finally, this script will call docker build .
    • Dockerfile: As usual, but depending on the number of commands we need to run we might have an install.sh
    • install.sh: This is copied and run inside the container, installs packages, removes unnecessary files, etc. Without being 100% sure - I think such an approach reduces the number of layers avoiding multiple commands in a single RUN
    • entrypoint.sh: Container's entrypoint. Allows us to perform tasks when the container starts (like parse environment variables) and print debugging info
    • 我发现上述结构很方便并且可以自我记录,因为团队中的每个人都可以构建任何图像(没有特殊说明/步骤).README 用于解释图像在做什么......但我不会骗你......它通常是空的......(或者有一个 h1 供 gitlab 显示):)

      I find the above structure convenient and self-documented since everyone in the team can build any image (no special instructions/steps). The README is there to explain what the image is doing... but I won't lie to you... it is usually empty... (or has an h1 for the gitlab to display) :)

      这篇关于在 docker build 期间在主机上执行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆