且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Docker的构建时创建动态环境变量

更新时间:2022-01-17 09:08:57

Docker v1.9或更新版本

Docker v1.9 or newer

如果您使用Docker v1.9或更新的,这可以通过支持构建时间参数来实现。参数在 Dockerfile 中由使用ARG语句

If you are using Docker v1.9 or newer, this is possible via support for build time arguments. Arguments are declared in the Dockerfile by using the ARG statement.

ARG REQUIRED_ARGUMENT
ARG OPTIONAL_ARGUMENT=default_value

当您稍后使用 docker build 构建您的图像时,可以通过标志 - build-arg ,如 docker docs 所述。

When you later actually build your image using docker build you can pass arguments via the flag --build-arg as described in the docker docs.

$ docker build --build-arg REQUIRED_ARGUMENT=this-is-required .

请注意,建议将使用构建时间变量密码或秘密,如密钥或凭据。

Please note that it is not recommended to use build-time variables for passwords or secrets such as keys or credentials.

此外,构建时变量可能具有对缓存有很大的影响。因此,Dockerfile应该非常小心,以便尽可能地利用缓存,并加快构建过程。

Furthermore, build-time variables may have great impact on caching. Therefore the Dockerfile should be constructed with great care to be able to utilize caching as much as possible and therein speed up the building process.

编辑:docker从 leedm777:s answer

如果您在1.9之前使用Docker版本,则 ARG / - build-arg 方法是不可能的。您在构建期间无法解决此类信息,因此您必须将它们作为参数传递给 docker运行命令。

If you are using a Docker-version before 1.9, the ARG/--build-arg approach was not possible. You couldn't resolve this kind of info during the build so you had to pass them as parameters to the docker run command.

Docker 图像在时间上是一致的,而容器可以被调整并被视为丢弃进程。

Docker images are to be consistent over time whereas containers can be tweaked and considered as "throw away processes".

  • More info about ENV
  • A docker discussion about dynamic builds

这个问题的旧解决方案是使用模板。这不是一个整洁的解决方案,但是当时是很少的可行选择之一。 (灵感来自此讨论)。

The old solution to this problem was to use templating. This is not a neat solution but was one of very few viable options at the time. (Inspiration from this discussion).


  1. 将所有动态数据保存在json或yaml文件中

  2. 创建一个docker文件template,其中动态可以稍后扩展

  3. 编写一个脚本,使用您熟悉的模板库从配置数据创建Dockerfile