How do I set environment variables during Docker build process?

ARG is for setting environment variables which are used during the docker build process – they are not present in the final image, which is why you don’t see them when you use docker run.

You use ARG for settings that are only relevant when the image is being built, and aren’t needed by containers which you run from the image. You can use ENV for environment variables to use during the build and in containers.

With this Dockerfile:

FROM ubuntu
ARG BUILD_TIME=abc
ENV RUN_TIME=123
RUN touch /env.txt
RUN printenv > /env.txt

You can override the build arg as you have done with docker build -t temp --build-arg BUILD_TIME=def .. Then you get what you expect:

> docker run temp cat /env.txt                                                                                         
HOSTNAME=b18b9cafe0e0                                                                                                  
RUN_TIME=123                                                                                                           
HOME=/root                                                                                                             
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin                                                      
BUILD_TIME=def                                                                                                         
PWD=/ 

Leave a Comment

tech