ENV vs ARG in Dockerfile: Key Differences and Usage
ARG defines variables available only during the image build process, while ENV sets environment variables that persist in the final image and are available at runtime. Use ARG for build-time configuration and ENV for runtime settings.Quick Comparison
Here is a quick side-by-side comparison of ENV and ARG in Dockerfiles.
| Factor | ARG | ENV |
|---|---|---|
| Scope | Available only during build | Available during build and runtime |
| Default Value | Can have default, overridden at build time | Set once, persists in image |
| Visibility | Not in final image environment | Included in final image environment |
| Usage | Configure build steps | Configure running container environment |
| Access | Used with ARG in Dockerfile | Used with ENV in Dockerfile and containers |
| Security | Can hide sensitive info from final image | Exposed in image and containers |
Key Differences
ARG variables are only available during the image build process. You can define them with optional default values and override them when running docker build using the --build-arg flag. Once the build finishes, ARG values are not accessible inside the running container.
On the other hand, ENV variables are baked into the image and persist in the container environment at runtime. They are used to set configuration values that the application inside the container can read when it runs.
Because ARG values do not persist in the final image, they are better for sensitive data or build-time options you don't want exposed. ENV variables are visible in the container environment and should be used for settings the app needs while running.
Code Comparison
FROM alpine:3.18 # Define build-time argument with default ARG APP_VERSION=1.0 # Use ARG in build step RUN echo "Building version $APP_VERSION" # Set environment variable for runtime ENV APP_VERSION=$APP_VERSION CMD ["sh", "-c", "echo Running app version $APP_VERSION"]
ARG Equivalent
FROM alpine:3.18 # Build-time argument with default ARG APP_VERSION=1.0 # Use ARG only during build RUN echo "Build-time version is $APP_VERSION" # No ENV set, so runtime variable is empty CMD ["sh", "-c", "echo Runtime version is $APP_VERSION"]
When to Use Which
Choose ARG when: you need variables only during the build process, such as selecting build options or passing secrets that should not be in the final image.
Choose ENV when: you want to set environment variables that your application or services inside the container will use at runtime.
In many cases, you can combine both: use ARG to pass build-time values and then assign them to ENV to make them available at runtime if needed.
Key Takeaways
ARG is for build-time variables, ENV is for runtime environment variables.ARG values do not persist in the final image; ENV values do.--build-arg to override ARG values during build.ENV variables are accessible inside running containers.ARG and ENV to pass build-time info to runtime if needed.