Docker ARG vs ENV
ARG and env can be confusing at first. Both are Dockerfile instructions which help you define variables, and from within the Dockerfile they feel pretty similar.
Let’s make sure that you understand the difference, and can use both of them comfortably to build better Docker images without repeating yourself.
ENV is for future running containers. ARG for building your Docker image.
ENV is mainly meant to provide default values for your future environment variables. Running dockerized applications can access environment variables. It’s a great way to pass configuration values to your project.
ARG values are not available after the image is built. A running container won’t have access to an ARG variable value. You can imagine the ARG and ENV as two overlapping rectangles:
Notice how both ARG and ENV overlap during the image build? This causes confusion sometimes: from within your Dockerfile, both ARG and ENV seem very similar. Both can be accessed from within your Dockerfile commands in the same manner.
ARG VAR_A 5 ENV VAR_B 6 RUN echo $VAR_A RUN echo $VAR_B
Just looking at the RUN commands, you couldn’t tell which one is an ARG and which one is an ENV variable.
You can’t change ENV directly during the build!
Build arguments can be set to a default value inside of a Dockerfile:
ARG VAR_NAME 5
but also changed by providing
--build-arg VAR_NAME=6 argument when you build your image. In a similar way, you can specify default values for ENV variables:
ENV VAR_NAME_2 6
But unlike ARG, you can’t override ENV values directly from the commandline when building your image. However, you can use ARG values to dynamically set default values of ENV variables during the build like this:
# You can set VAR_A while building the image # or leave it at the default ARG VAR_A 5 # VAR_B gets the (overridden) value of VAR_A ENV VAR_B $VAR_A
You can read about it in more detail here.
Want to learn more?
Docker ENV and ARG can be confusing at first. I hope that this brief explanation has helped you understand the difference.
Remember, that environment variables can be changed after your Docker image is built! You can override ENV values which were set in a Dockerfile by providing new environment variable values through the Docker CLI or your docker-compose.yml file.
Would you like to learn more about Docker ARG, ENV, env_file and docker-compose .env files? Check out this in-depth guide to get a complete overview of the topic, so you have less trouble to build your Docker images and configure dockerized apps.