更新时间: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".
这个问题的旧解决方案是使用模板。这不是一个整洁的解决方案,但是当时是很少的可行选择之一。 (灵感来自此讨论)。
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).