vsupalov


Setting Default Docker Environment Variables During Image Build

How to pass custom values to ENV variables when you execute 'docker build' to create your image.

[ docker ]

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.

Get My Weekly Newsletter

Weekly-ish articles about Kubernetes, Docker, DevOps, automation and deployment.

Free goodies too: get a list of my top 12 tools for deployment & automation and more exclusive content I only share with subscribers.