Setting an environment variable using the ENV instruction creates a new layer in the Docker image. The variable is then persisted for all subsequent build stages and is also present in the resulting image. Calling RUN unset <env-variable> unsets the variable only for this particular layer, but it is still possible to dump the environment variable from the previous layer.

Why is this an issue?

The environment variables often contain secrets, tokens, and other sensitive information. They are present in the containers and could be dumped anytime. Calling unset doesn’t prevent this information from being hidden for other commands.

How to fix it

If an environment variable is needed only during build, this variable should be set and unset in a single RUN instruction.

Code examples

Noncompliant code example

ENV $ADMIN_USER
RUN unset $ADMIN_USER

Compliant solution

RUN export ADMIN_USER="admin" \
    && ... \
    && unset ADMIN_USER

How does this work?

In this example, the visibility of ADMIN_USER is only limited to the single layer. However, it is still possible to extract the value from the image. The best solution is to use ARG instead of ENV or set and unset the variable in the same RUN instruction.

Resources

Documentation