Setting Default Docker Environment Variables During Image Build
Docker ARG and ENV can be a frustrating topic. You can only set ARG values while building the image, and only ENV values are used to set environment variables in running containers.
What if you want to specify default ENV values while building your Docker image? Do you really need to edit your Dockerfile every single time?
Good news! You don’t need dust off your sed skills and write bash scripts with nasty regular expressions in them. 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.
While you can’t directly set ENV variable values when running
docker build, you can
use ARG to pass through
--build-arg values right into your ENV instructions.
First, you’ll need to define an additional ARG variable, which is only there to pass through the value to your environment variable:
ARG buildtime_variable=default_value # <- this one's new ENV env_var_name=$buildtime_variable # we reference it directly
Almost done! Now, when you’re building your image you can override the default_value of “buildtime_variable” any time you like:
$ docker build --build-arg buildtime_variable=a_value # ... the rest of the build command is omitted
You can change the value each time you run
docker build without editing the Dockerfile.
The ARG variable “buildtime_variable” will be set to your dynamic value and the ENV variable “env_var_name” will be set to the fresh ARG value.
Want to Learn More?
I hope you can use this trick to avoid having to hardcode your ENV values and fixup commits to update the darn Dockerfile.
If ARG and ENV still feel confusing to you, check out this brief explanation of how they differ. Don’t worry, once you really understand how they work they will be a useful tool to make your Dockerfiles easier to handle.
Are you sick of debugging Docker ARG, ENV, env_file and docker-compose .env issues? Level up your skills and fix them for good with the help of this in-depth guide.