Dockerfile: 在单行中设置多个环境变量

我的印象是,环境变量可以设置在一个单一的行如下,以尽量减少中间图像。

FROM alpine:3.6
ENV RUBY_MAJOR 2.4 \
RUBY_VERSION 2.4.1 \
RUBY_DOWNLOAD_SHA256 4fc8a9992de3e90191de369270ea4b6c1b171b7941743614cc50822ddc1fe654 \
RUBYGEMS_VERSION 2.6.12 \
BUNDLER_VERSION 1.15.3

但是,在这个代码片段的基础上运行一个容器并调用 # set |grep RU,我发现这些变量没有单独分配,而是合并成一个字符串。

RUBY_MAJOR='2.4     RUBY_VERSION 2.4.1     RUBY_DOWNLOAD_SHA256 4fc8a9992de3e90191de369270ea4b6c1b171b7941743614cc50822ddc1fe654     RUBYGEMS_VERSION 2.6.12     BUNDLER_VERSION 1.15.3'

但是,如果我显式地将每个变量设置为下面这样,我就会得到预期的输出,并且在调用这些变量时不会出现错误。

ENV RUBY_MAJOR 2.4
ENV RUBY_VERSION 2.4.1
ENV RUBY_DOWNLOAD_SHA256 4fc8a9992de3e90191de369270ea4b6c1b171b7941743614cc50822ddc1fe654
ENV RUBYGEMS_VERSION 2.6.12
ENV BUNDLER_VERSION 1.15.3

问: 是否可以将环境变量的设置组合在一行上?如果是这样,我该怎么做?这是个好习惯吗?

82364 次浏览

There are two formats for specifying environments. If you need single variable then you below format

ENV X Y

This will assign X as Y

ENV X Y Z

This will assign X as Y Z

If you need to assign multiple environment variables then you use the other format

ENV X=Y Z=A

This will assign X as Y and Z as A. So your Dockerfile should be

FROM alpine:3.6
ENV RUBY_MAJOR=2.4 \
RUBY_VERSION=2.4.1 \
RUBY_DOWNLOAD_SHA256=4fc8a9992de3e90191de369270ea4b6c1b171b7941743614cc50822ddc1fe654 \
RUBYGEMS_VERSION=2.6.12 \
BUNDLER_VERSION=1.15.3


RUN env

You do not need to worry about many ENV commands each creating a new intermediate layer for your final image created by your Dockerfile.

from Best practices for writing Dockerfiles

Minimize the number of layers

Prior to Docker 17.05, and even more, prior to Docker 1.10, it was important to minimize the number of layers in your image. The following improvements have mitigated this need:

  • In Docker 1.10 and higher, only RUN, COPY, and ADD instructions create layers. Other instructions create temporary intermediate images, and no longer directly increase the size of the build.

  • Docker 17.05 and higher add support for multi-stage builds, which allow you to copy only the artifacts you need into the final image. This allows you to include tools and debug information in your intermediate build stages without increasing the size of the final image.