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.

Master Docker ARG and ENV in 5 Days!

Sign up to the free 5-day email course, and learn more about using environment and build-time variables with Docker. Get actionable advice, best practices and nifty tricks to use for your next project.

Privacy and your data: I use the US-provider ConvertKit as my email marketing automation platform. 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.

You can get more information about the usage of your data, logging of your registration, sending out mails with the US-provider ConvertKit, statistical analysis around emails and the possibility to unsubscribe in my Privacy Policy.

We won't send you spam. Unsubscribe at any time. Powered by ConvertKit