深度阅读

How to use ARG and ENV in a Dockerfile?

作者
作者
2023年08月22日
更新时间
13.25 分钟
阅读时间
0
阅读量

To use ARG and ENV in a Dockerfile, you can follow these steps:

  1. Define one or more ARG instructions to allow users to pass in variables at build-time using the --build-arg flag.
ARG VERSION=default
  1. Use the ARG variables in your Dockerfile to specify the default value for an environment variable using the ENV instruction.
ENV MY_VERSION=$VERSION
  1. Optionally, you can also specify a default value for the ARG variables by adding a value after the variable name.
ARG VERSION=default
ENV MY_VERSION=${VERSION:-3.0.0}
  1. Build your Docker image, passing in any desired values for the ARG variables using the --build-arg flag.
docker build --build-arg VERSION=2.0.0 -t myimage .

This will build your Docker image, using the value 2.0.0 for the VERSION ARG variable, and set the MY_VERSION environment variable to the same value.

Using ARG and ENV in a Dockerfile can make your image more flexible, allowing you to specify environment variables at build-time while keeping the rest of the Dockerfile static.

Note that it’s generally not recommended to store sensitive information, such as passwords, in ARG or ENV variables because they can be viewed using the docker history command or by inspecting the image layers, respectively.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。