How to use environment variables in a Dockerfile?
Published on Aug. 22, 2023, 12:19 p.m.
To use environment variables in a Dockerfile, you can follow these steps:
- Set the value of your environment variable using the
ENV
instruction in your Dockerfile.
ENV MY_VAR=my_value
Alternatively, you can use the ARG
instruction to allow users to set the value at build time using the --build-arg
flag.
ARG MY_VAR
ENV MY_VAR=${MY_VAR}
- Use the environment variable in your Dockerfile by referencing it using the
${variable_name}
syntax.
RUN echo "The value of MY_VAR is ${MY_VAR}"
- Build your Docker image, either passing in the environment variable value using the
--build-arg
flag (if usingARG
), or using the default value specified in theENV
instruction.
docker build --build-arg MY_VAR=custom_value -t myimage .
By using environment variables in your Dockerfile, you can make your images more flexible and easier to manage by allowing users to customize the behavior of the container at runtime. This can be especially useful for applications that require different settings in different environments or for handling sensitive information like passwords or keys.
Note that environment variables set in the Dockerfile can be viewed using the docker inspect
command or by inspecting the image layers, so make sure to avoid including sensitive information in them. It’s also important to be consistent with variable names and uses across your Dockerfile, so that you can manage them more easily.