vsupalov

Setting Default Docker Environment Variables During Image Build

Environment variables are available to processes running inside of Docker containers. You can set a value inside of a Dockerfile using the ENV directive, or provide a dynamic value when launching a Docker container from an image, using the -e flag, an env_file or from your docker-compose.yml file.

But is there a way to set the value of an environment variable when you build the image so it sticks around and will be available to containers started from it, if not overridden? Do you need to hardcode the value, and edit your Dockerfile every time you’re building a new image? Gosh, is it time to dust off your sed skills and write bash scripts with regular expressions?

Nope. There’s a convenient ways to set the default values of an ENV variable inside of your Dockerfile, and get the value from a command-line argument when you’re building the image. The secret lies in combining the ENV and ARG directives. Your Dockerfile should contain something similar to the following two lines:

ARG buildtime_variable=default_value
ENV env_var_name=$buildtime_variable

When you’re building your image, you can override the default_value directly from the command line:

$ docker build --build-arg buildtime_variable=a_value # [...]

The value of the ARG variable will be overridden with the one you provided, and during the build the ENV value will be set to your provided value as well. Although the ARG variable will not be available to future containers, the passed ENV value will be there to be used. Once you run the container, you’ll have a default value for the environment variable, unless you choose to override it.

Join the mailing list!


Subscribe to get notified about future articles and stay in touch via email.

I write about Kubernetes, Docker, automation- and deployment topics, but would also like to keep you up to date about news around the business-side of things.

I won't send you spam. Unsubscribe at any time. You can get more information about the usage of your data, the storage of your registration, sending out mails with the US-provider ConvertKit, statistical analysis of emails sent and your possibility to unsubscribe in my Privacy Policy.

I use the US-provider ConvertKit for email automation. By clicking to submit this form, you acknowledge that the information you provide will be transferred to ConvertKit for processing in accordance with their Privacy Policy and Terms.

Powered by ConvertKit