When building an image using Dockerfile, you sometimes need to set environment variables inside the container.

The ENV directive has the following format:

ENV <key>=<value> ...
Copy the code

The ENV directive sets the environment variable

to the value

. This value will be used in the context of all subsequent instructions during the construction phase, and can be substituted for other instructions. This value will be interpreted as other environment variables, so if the quote characters are not escaped, they will be removed. Like command line parsing, quotes and backslashes can be used to include Spaces in values.

Such as:

ENV MY_NAME="John Doe"
ENV MY_DOG=Rex\ The\ Dog
ENV MY_CAT=fluffy
Copy the code

The ENV directive allows multiple

=

… Variables are set at the same time. The following example will produce the same result in the generated image:

ENV MY_NAME="John Doe" MY_DOG=Rex\ The\ Dog \
    MY_CAT=fluffy
Copy the code

When a container is run with a generated image, environment variables set with ENV are persisted in the container. You can view these values using Docker Inspect and modify them using docker run –env

=

.

Persistence of environment variables can cause unexpected side effects. For example, setting ENV DEBIAN_FRONTEND=noninteractive changes the behavior of apt-get and can be confusing to users using mirroring.

If environment variables are required only during the build process, and not in the final image, consider setting a value for a single command:

RUN DEBIAN_FRONTEND=noninteractive apt-get update && apt-get install -y ...
Copy the code

Or use ARG, which does not persist in the final image:

ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y ...
Copy the code

Alternative syntax

The ENV directive also allows another syntax, ENV


, which omits the middle equals sign. Such as:

ENV MY_VAR my-value
Copy the code

This syntax does not allow setting more than one environment variable in a single ENV directive, which can cause confusion. For example, the following code sets an environment variable (ONE) with a value of “TWO= THREE=world” :

ENV ONE TWO= THREE=world
Copy the code

This alternative syntax is supported for backward compatibility, but is discouraged for the above reasons and may be removed in future releases.

Original link: k8scat.com/posts/docke…